Numpy Operations
We can do operations on an array as a whole. In this section we look at some examples.
Array Operations
The addition +
and multiplication *
operators are componentwise on NumPy arrays.
Output:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Output:
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
Output:
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
Both subtraction -
and division /
operators work as well, with the usual restriction on division by 0. In the case of 0/0 the object returned is nan
, whereas 1/0 returns inf
.
Output:
array([nan, 1., 1., 1., 1., 1., 1., 1., 1., 1.])
To concatenate two arrays there is the .concatenate()
method.
Output:
array([1, 2, 3, 4, 5, 6])
Array with Scalar Operations
All scalar arithmetic operations are performed componentwise too.
Output:
array([ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
Output:
array([ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27])
Output:
array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6])
Output:
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
Output:
array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
We can combine these arithmetic operations with broadcasting as follows.
Output:
array([ 0, 1, 200, 300, 400, 500, 6, 7, 8, 9])
Universal Array Functions
NumPy has many universal array functions, which are mathematical functions you can perform across the array.
Output:
array([ 0. , 1. , 1.41421356, 1.73205081,
2. , 2.23606798, 2.44948974, 2.64575131,
2.82842712, 3. ])
Similarly there is .exp()
, .max()
, .sin()
, .log()
, etc. For a comprehensive list of universal array functions see: https://numpy.org/doc/stable/reference/ufuncs.html.
As a final example, we look at how the universal array function .sum()
can be used to sum all entries in an array, or to sum along columns (axis = 0
) or rows (axis = 1
).
Output:
array([[2., 2., 2., 2.],
[2., 2., 2., 2.],
[2., 2., 2., 2.]])
Output:
24.0
Output:
array([6., 6., 6., 6.])
Output:
array([8., 8., 8.])