Basic Operations
Basic Operations
So far you have seen how to create a new NumPy array and how items are defined in it.
Now it is the time to see how to apply various operations to them.
Arithmetic Operators
The first operations that you will perform on arrays are the arithmetic operators. The
most obvious are adding and multiplying an array by a scalar.
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> a+4
array([4, 5, 6, 7])
>>> a*2
array([0, 2, 4, 6])
These operators can also be used between two arrays. In NumPy, these operations
are element-wise, that is, the operators are applied only between corresponding
elements. These are objects that occupy the same position, so that the end result will be
a new array containing the results in the same location of the operands (see Figure 3-1).
>>> b = np.arange(4,8)
>>> b
array([4, 5, 6, 7])
>>> a + b
array([ 4, 6, 8, 10])
>>> a – b
array([–4, –4, –4, –4])
>>> a * b
array([ 0, 5, 12, 21])
Moreover, these operators are also available for functions, provided that the value
returned is a NumPy array. For example, you can multiply the array by the sine or the
square root of the elements of array b.
>>> a * np.sin(b)
array([–0. , –0.95892427, –0.558831 , 1.9709598 ])
>>> a * np.sqrt(b)
array([ 0. , 2.23606798, 4.89897949, 7.93725393])
Moving on to the multidimensional case, even here the arithmetic operators
continue to operate element-wise.