Python NumPy provides basic maths operations and functions with arrays.
Arithmetic operation with arrays
- NumPy arrays can have arithmetic operations. In example below, we can add a value of 1 to all the elements of array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# import numpy library as np import numpy as np # Create an array of my_array = np.array([1,2,4,6]) # Above will create an array like this [1 2 4 6] # add number 2 to each value of array print(my_array + 2) print() # multiply number 2 to each value of array print(my_array * 2) print() # divide by 2 each value of array print(my_array / 2) print() # Maths sin function print(np.sin(my_array)) print() # Maths Exponents print(np.exp(my_array)) print() # Maths Logarithms print(np.log(my_array + 2)) print() # Maths Square Roots print(np.sqrt(my_array)) print() # Maths Squared print(np.square(my_array)) |
The above code will output this result
[3 4 6 8]
[ 2 4 8 12]
[0.5 1. 2. 3. ]
[ 0.84147098 0.90929743 -0.7568025 -0.2794155 ]
[ 2.71828183 7.3890561 54.59815003 403.42879349]
[1.09861229 1.38629436 1.79175947 2.07944154]
[1. 1.41421356 2. 2.44948974]
[ 1 4 16 36]
More functions on arrays
There are many more functions that be performed using numpy. In example below, we are creating a two dimensional array and then performing some useful functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# import numpy library as np import numpy as np # using randint, generate an array with 100 rows and 10 columns of numbers from 0 to 1. rand_array = np.random.randint(0, 2, size = (10, 6)) print(rand_array) print() # Sum of all elements in array print(rand_array.sum()) # Minimum value in array print(rand_array.min()) # Maximum value in array print(rand_array.max()) # total elements in array print(rand_array.size) # add all numbers in array in x-axis and create an array print(rand_array.sum(axis=1)) # average of all numbers in array = sum/total elements print(rand_array.mean()) # Standard Deviation (square root of Variance) value in array print(rand_array.std()) # median (The middle value of a sorted list of numbers) value in array print(np.median(rand_array)) # counts the occurrence of each element in array bin_array = [1,2,4,5,9] print(np.bincount(bin_array)) |
The above code will output this result
[[0 1 1 0 1 1]
[1 1 0 1 1 0]
[1 0 0 1 1 0]
[0 1 1 0 1 0]
[1 0 1 1 1 1]
[1 0 1 1 1 1]
[0 0 1 1 1 0]
[1 0 0 1 0 0]
[0 0 0 0 0 1]
[1 0 1 0 1 0]]
33
0
1
60
[4 4 3 3 5 5 3 2 1 3]
0.55
0.49749371855331
1.0
[0 1 1 0 1 1 0 0 0 1]