Skip to content

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.

import numpy as np
arr = np.arange(0,10)
arr
Output:
array([ 0,  1,  2,  3,  4, 5, 6, 7, 8, 9])
arr + arr
Output:
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])
arr * arr
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.

arr/arr
Output:
array([nan,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

To concatenate two arrays there is the .concatenate() method.

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1,arr2))
arr
Output:
array([1, 2, 3, 4, 5, 6])

Array with Scalar Operations

All scalar arithmetic operations are performed componentwise too.

3 + arr
Output:
array([ 3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
3 * arr
Output:
array([ 0,  3,  6,  9, 12, 15, 18, 21, 24, 27])
arr - 3
Output:
array([-3, -2, -1,  0,  1,  2,  3,  4,  5,  6])
arr**2
Output:
array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])
arr/2
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.

arr[2:6] *= 100
arr
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.

np.sqrt(arr)
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).

arr = np.ones(12).reshape(3,4)*2
arr
Output:
array([[2., 2., 2., 2.],
       [2., 2., 2., 2.],
       [2., 2., 2., 2.]])
arr.sum()   # sum over all entries
Output:
24.0
arr.sum(axis = 0) # sum along columns
Output:
array([6., 6., 6., 6.])
arr.sum(axis = 1)   # sum along rows
Output:
array([8., 8., 8.])