One of the great advantages of Numpy arrays is that they allow one to very easily apply mathematical operations to entire arrays effortlessly. We are presenting here 3 ways in which this can be done.
import numpy as np
To illustrate how arrays are useful, let's first consider the following problem. You have a list:
mylist = [1,2,3,4,5]
And now you wish to add to each element of that list the value 3. If we write:
mylist + 3
We receive an error because Python doesn't know how to combine a list with a simple integer. In this case we would have to use a for loop or a comprehension list, which is cumbersome.
[x + 3 for x in mylist]
Let's see now how this works for an array:
myarray = np.array(mylist)
myarray + 3
Numpy understands without trouble that our goal is to add the value 3 to each element in our list. Naturally this is dimension independent e.g.:
my2d_array = np.ones((3,6))
my2d_array
my2d_array + 3
Of course as long as we don't reassign this new state to our variable it remains unchanged:
my2d_array
We have to write:
my2d_array = my2d_array + 3
my2d_array
Naturally all basic operations work:
my2d_array * 4
my2d_array / 5
my2d_array ** 5
In addition to simple arithmetic, Numpy offers a vast choice of functions that can be directly applied to arrays. For example trigonometry:
np.cos(myarray)
Exponentials and logs:
np.exp(myarray)
np.log10(myarray)
If we use a logical comparison on a regular variable, the output is a boolean (True or False) that describes the outcome of the comparison:
a = 3
b = 2
a > 3
We can do exactly the same thing with arrays. When we added 3 to an array, that value was automatically added to each element of the array. With logical operations, the comparison is also done for each element in the array resulting in a boolean array:
myarray = np.zeros((4,4))
myarray[2,3] = 1
myarray
myarray > 0
Exactly as for simple variables, we can assign this boolean array to a new variable directly:
myboolean = myarray > 0
myboolean
The operations described above were applied element-wise. However sometimes we need to do operations either at the array level or some of its axes. For example, we need very commonly statistics on an array (mean, sum etc.)
nd_array = np.random.normal(10, 2, (3,4))
nd_array
np.mean(nd_array)
np.std(nd_array)
Or the maximum value:
np.max(nd_array)
Note that several of these functions can be called as array methods instead of numpy functions:
nd_array.mean()
nd_array.max()
Note that most functions can be applied to specific axes. Let's remember that our arrays is:
nd_array
We can for example do a maximum projection along the first axis (rows): the maximum value of eadch column is kept:
proj0 = nd_array.max(axis=0)
proj0
proj0.shape
We can of course do the same operation for the second axis:
proj1 = nd_array.max(axis=1)
proj1
proj1.shape
There are of course more advanced functions. For example a cumulative sum:
np.cumsum(nd_array)