Today we’ll be talking about numerical operations on numpy arrays with scalars.
Scalars are numbers like integers or floats as opposed to arrays. If we perform an operation on a scalar and an array, the operation is performed elementwise, so on each element of the array. For example, if we multiply a scalar and an array, the scalar is multiplied by each number in the array. The other operations work exactly the same.
Here are some examples:
Let’s create a list and turn it to a numpy array:
>>> import numpy as np
>>> nums = [2, 5, 8.5, 12.25, 20]
>>> n = np.array(nums)
>>> print(n)
[ 2. 5. 8.5 12.25 20. ]
Let’s see how addition works:
>>> m = n + 10
>>> print(m)
[12. 15. 18.5 22.25 30. ]
What about subtraction?
>>> k = n - 2
>>> print(k)
[ 0. 3. 6.5 10.25 18. ]
As you probably expect, multiplication works exactly the same:
>>> n = n * 10
>>> print(n)
[ 20. 50. 85. 122.5 200. ]
And so does division, both true division:
>>> p = n / 5
>>> print(p)
[ 4. 10. 17. 24.5 40. ]
and floor division:
>>> r = p // 4
>>> print(r)
[ 1. 2. 4. 6. 10.]
Here’s an example with exponentiation:
>>> s = n ** 3
>>> print(s)
[ 8000. 125000. 614125. 1838265.625 8000000. ]
and one more with modulus:
>>> t = s % 100
>>> print(t)
[ 0. 0. 25. 65.625 0. ]
And here’s a slightly more complex example with a multidimensional array and two operations, multiplication and addition:
>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> print(x)
[[1 2 3]
[4 5 6]
[7 8 9]]
>>> y = 5 * x + 1
>>> print(y)
[[ 6 11 16]
[21 26 31]
[36 41 46]]
Here’s the video version of the article: