Python - Array Operations

Array Operations

Example : With Scalars
import numpy as np
x = np.arange(6).reshape(2,3)
print(x + 10, end='\n\n') # adds 10 to each element
print(x * 3, end='\n\n')  # multiplies each element by 3
print(x % 2)              # performs modulo of 2 on each element
Output
[[10 11 12]
 [13 14 15]]
[[ 0  3  6]
 [ 9 12 15]]
[[0 1 0]
 [1 0 1]]
Example : With Array of same size
import numpy as np
x = np.array([[-1, 1], [-2, 2]])
y = np.array([[4, -4], [5, -5]])
print(x + y, end='\n\n')
print(x * y)
Output
[[ 3 -3]
 [ 3 -3]]
[[ -4  -4]
 [-10 -10]]
Example : With Array of different size
import numpy as np
x = np.array([[-1, 1], [-2, 2]])
y = np.array([-10, 10])
print(x * y)
Output
[[10 10]
 [20 20]]
Example : Sum
import numpy as np
x = np.array([[0,1], [2, 3]])
print(x.sum(), end='\n\n')
print(x.sum(axis=0), end='\n\n')
print(x.sum(axis=1))
Output
6
[2 4]
[1 5]

No comments:

Post a Comment