Note
Go to the end to download the full example code.
12.3.10.2.5. Operations#
import numpy as np
Arithmetic
array = np.array([20, 30, 40, 50])
array2 = np.arange(4)
array2 - array
array([-20, -29, -38, -47])
array2**2
array([0, 1, 4, 9])
10 * np.sin(array)
array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])
array < 35
array([ True, True, False, False])
Matrix operations
elementwise product
A = np.array([[1, 1], [0, 1]])
B = np.array([[2, 0], [3, 4]])
A * B
array([[2, 0],
[0, 4]])
matrix product
A @ B
A.dot(B)
array([[5, 4],
[3, 4]])
Inline operation
randVal = np.random.default_rng(1)
a = np.ones((2, 3), dtype=int)
b = randVal.random((2, 3))
a *= 3
a
array([[3, 3, 3],
[3, 3, 3]])
b += a
b
array([[3.51182162, 3.9504637 , 3.14415961],
[3.94864945, 3.31183145, 3.42332645]])
Operations on all elements
a = randVal.random((2, 3))
a.sum()
3.1057109529998157
a.min()
0.027559113243068367
a.mean()
0.5176184921666359
a.max()
0.8277025938204418
b = np.arange(12).reshape(3, 4)
b.sum(axis=0) # sum of each column
b.min(axis=1) # min of each row
b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38]])
Universal functions
B = np.arange(3)
np.exp(B)
array([1. , 2.71828183, 7.3890561 ])
np.sqrt(B)
array([0. , 1. , 1.41421356])
C = np.array([2.0, -1.0, 4.0])
np.add(B, C)
array([2., 0., 6.])
Total running time of the script: (0 minutes 0.019 seconds)