Operations In Numpy
Arrays in numpy are quite flexible in its dealing with another array or a scaler. Let us see some array to array operations. Let us begin with addition and subtraction of two arrays.
import numpy as np
arr = np.arange(0,11)
print(arr+arr)
print(arr-arr)
Output :
[ 0 2 4 6 8 10 12 14 16 18 20]
[0 0 0 0 0 0 0 0 0 0 0]
Numpy also allows product of two arrays .
import numpy as np
arr_1 = np.arange(0,11)
arr_2 = np.arange(10,21)
print(arr_1 * arr_2)
Output :
[ 0 11 24 39 56 75 96 119 144 171 200]
It is also possible to divide two arrays. Let us see how.
import numpy as np
arr_1 = np.arange(0,11)
arr_2 = np.arange(10,21)
print( arr_1 / arr_2 )
Output :
[0. 0.09090909 0.16666667 0.23076923 0.28571429 0.33333333
0.375 0.41176471 0.44444444 0.47368421 0.5 ]
All mathematical operations can also be performed between an array and an scaler.
import numpy as np
arr_1 = np.arange(0,11)
print( arr_1 + 5 )
print( arr_1 * 5 )
print( arr_1 - 5 )
print( arr_1 / 5 )
Output :
[ 5 6 7 8 9 10 11 12 13 14 15]
[ 0 5 10 15 20 25 30 35 40 45 50]
[-5 -4 -3 -2 -1 0 1 2 3 4 5]
[0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. ]
Functional operations on arrays
min and max :
import numpy as np
arr_1 = np.arange(0,11)
print(np.min(arr_1))
print(np.max(arr_1))
Output :
0
10
sqrt :
import numpy as np
arr_1 = np.arange(0,11)
print(np.sqrt(arr_1))
Output :
[0. 1. 1.41421356 1.73205081 2. 2.23606798
2.44948974 2.64575131 2.82842712 3. 3.16227766]
trignometric functions like sin and tan are also built in numpy.
sin and tan :
import numpy as np
arr_1 = np.arange(0,11)
print(np.sin(arr_1))
print()
print(np.tan(arr_1))
Output :
[ 0. 0.84147098 0.90929743 0.14112001 -0.7568025 -0.95892427
-0.2794155 0.6569866 0.98935825 0.41211849 -0.54402111]
[ 0. 1.55740772 -2.18503986 -0.14254654 1.15782128 -3.38051501
-0.29100619 0.87144798 -6.79971146 -0.45231566 0.64836083]
exp :
The exponential value function .
import numpy as np
arr_1 = np.arange(0,11)
print(np.exp(arr_1))
Output :
[1.00000000e+00 2.71828183e+00 7.38905610e+00 2.00855369e+01
5.45981500e+01 1.48413159e+02 4.03428793e+02 1.09663316e+03
2.98095799e+03 8.10308393e+03 2.20264658e+04]
abs :
Absolute value function - returns the absolute value of a number
import numpy as np
arr_1 = np.arange(-5,5)
print(np.abs(arr_1))
Output :
[5 4 3 2 1 0 1 2 3 4]
Popular Tutorials