Conditional Numpy array operations
In this recent article, we discussed the basic principles of Numpy arrays and how to work with them. Now it is time to venture somewhat beyond that by manipulating the contents of arrays based on conditions. And the best thing is that this can be done pretty much with a singular, albeit very powerful, command by the unassuming name of where. (To the SQL cracks out there such a command might sound comfortably familiar…)
Consider this simple example: You have a vector (yes, I admit, I come from the MATLAB camp, but I am working on it) of numbers 0 to 10 and want to set all numbers above 5 to 0. (OK, updating these few items by hand would definitely be easier, but such a manual way of doing things doesn’t scale too well.)
First we create the array:
And we have to wait no longer before anticipation and tension get unbearable: Call in the where function. Its arguments are absolutely straightforward (the hallmark of Python as we know it): condition, value if condition is met, value if condition is not met.
Simple, efficient, almost beautiful.
An alternative to the where method would be a combination between classical indexing and conditional operations.
This method is able to deliver the same result in our example, but it is much more limited than its mighty where sibling. In particular, by referring to the array by way of indexing it is not possible to handle the original array in a stepwise fashion. It gets clearer with another example: Say you don’t want to set all the numbers above 5 in our array to 0, but instead the task is to multiply each element above 5 with 10.
e1[e1>5] = e1*10 might seem only sensible. But it simply doesn’t work. We need where once again:
Nice and well, you say. Just another trick up the sleeve I never cared about not being aware of it. Is there any meaningful application?
Get Thomas Gamsjäger’s stories in your inbox
Join Medium for free to get updates from this writer.
Glad you asked.
A sine wave, rectified
In another recent article ‘Elementary signal generation with Python’ I introduced a few of the most common types of signals, first and foremost, the sine wave.
Here is the code for a sine wave with a frequency of 2, an amplitude of 1and a duration of also 2:
And here is the plot:
Now consider the following task: As nice such a sine wave might be, we want to get rid of those parts of the oscillations that plunge into the negative. As in the real world: From your energy provider, you get electricity in perfect sine wave fashion, also known as alternating current or AC. But every so often not AC is what you need, but DC, direct current, i.e. with no negative voltages. (Granted, the forefathers of electricity didn’t get the nomenclature overly consistent.) Where you need certain hardware to achieve that for real, most notably a diode (and a transformer, capacitors, wires etc. to produce usable DC, and the willingness to find your way into the lowly workshop), you can create precisely such a signal with just one additional line of code. It is the one numbered 10 in the code box below where our new signal2 is defined.
With that, you have just built nothing less than a half-wave rectifier, at least a virtual one.
And if you want to know how to save your Matplotlib plots in high quality format as separate files in order to use them on, say, Medium: Name the plot explicitly as infig1 = plt.figure() and save it with the method fig1.savefig('file name', dpi = 300) with your desired resolution in dots per inch (dpi). 300 dpi is a good choice to begin with. Or even simpler: Place plt.savefig('file name', dpi = 300) right before plt.show() . In this case, Python knows which plot to save even without naming it explicitly.
To conclude: Changing the contents of an array is an important operation. If you want to do that based on some condition, the where command will always be there to help.
Featured image: An array with two rows and three columns of — you keenly spotted it right away — drink cans, in this peculiar configuration classically and affectionately known as a six-pack. The Boolean state with respect to being open or closed can quite clearly be delineated even by the modestly trained human being, but which might at the same time be an interesting task for a machine learning algorithm. But rest assured, to propel the two still solidly sealed cans at positions (0, 0) and (1, 2) to a state of being opened and emptied no Python programming skills whatsoever will be required.







