12.3.2.7. OperationsΒΆ

import numpy as np

Arithmetic

array = np.array([20, 30, 40, 50])
array2 = np.arange(4)
array2 - array

Out:

array([-20, -29, -38, -47])
array2**2

Out:

array([0, 1, 4, 9])
10 * np.sin(array)

Out:

array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
array < 35

Out:

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

Out:

array([[2, 0],
       [0, 4]])

matrix product

A @ B
A.dot(B)

Out:

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

Out:

array([[3, 3, 3],
       [3, 3, 3]])
b += a
b

Out:

array([[3.51182162, 3.9504637 , 3.14415961],
       [3.94864945, 3.31183145, 3.42332645]])

Operations on all elements

a = randVal.random((2, 3))
a.sum()

Out:

3.1057109529998157
a.min()

Out:

0.027559113243068367
a.mean()

Out:

0.5176184921666359
a.max()

Out:

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

Out:

array([[ 0,  1,  3,  6],
       [ 4,  9, 15, 22],
       [ 8, 17, 27, 38]])

Univeral functions

B = np.arange(3)
np.exp(B)

Out:

array([1.        , 2.71828183, 7.3890561 ])
np.sqrt(B)

Out:

array([0.        , 1.        , 1.41421356])
C = np.array([2., -1., 4.])
np.add(B, C)

Out:

array([2., 0., 6.])

Total running time of the script: ( 0 minutes 0.008 seconds)

Gallery generated by Sphinx-Gallery