Today we’ll be talking about operations on two numpy arrays.
It’s pretty easy to perform operations on two numpy arrays. The operations are then performed elementwise, so on elements at the same positions in either array.
Here are some examples:
First let’s define our two arrays:
>>> a = np.array([2, 4, 6, 8, 10])
>>> b = np.array([1, 2, 3, 4, 5])
>>> print(a)
[ 2 4 6 8 10]
>>> print(b)
[1 2 3 4 5]
Let’s start with addition:
>>> c = a + b
>>> print(c)
[ 3 6 9 12 15]
And now let’s see how subtraction works:
>>> d = a - b
>>> print(d)
[1 2 3 4 5]
Here’s multiplication:
>>> e = a * b
>>> print(e)
[ 2 8 18 32 50]
And here’s true division:
>>> f = a / b
>>> print(f)
[2. 2. 2. 2. 2.]
You can also perform the operation of exponentiation:
>>> g = a ** b
>>> print(g)
[ 2 16 216 4096 100000]
It’s also possible to make complex expressions with both arrays and scalars:
>>> print(5 * a + (b ** 2) - a)
[ 9 20 33 48 65]
Here are some examples with multidimensional arrays:
>>> x = np.array([[2, 4, 6], [3, 6, 9]])
>>> y = np.array([[5, 10, 15], [4, 8, 12]])
>>> print(x)
[[2 4 6]
[3 6 9]]
>>> print(y)
[[ 5 10 15]
[ 4 8 12]]
>>> print(x + y)
[[ 7 14 21]
[ 7 14 21]]
>>> print(x * y)
[[ 10 40 90]
[ 12 48 108]]
As the operations are performed elementwise, the arrays should have tha same shapes. Otherwise, we get an error:
>>> m = np.array([2, 4, 6, 8])
>>> n = np.array([5, 10])
>>> print(m + n)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (2,)
Here’s the video version of the article: