English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
It should be noted that the arrays must have the same shape or conform to the array broadcasting rules.
import numpy as np a = np.arange(9, dtype = np.float_).reshape(3,3) print('First array:') print(a) print('\n') print('Second array:') b = np.array([10,10,10] print(b) print('\n') print ('Two arrays are added together:') print (np.add(a,b)) print('\n') print ('Two arrays are subtracted from each other:') print (np.subtract(a,b)) print('\n') print ('Two arrays are multiplied by each other:') print (np.multiply(a,b)) print('\n') print ('Two arrays are divided by each other:') print (np.divide(a,b))
The output result is:
First array: [[0. 1. 2.]] [3. 4. 5.]] [6. 7. 8.]] Second array: [10 10 10] Two arrays are added together: [[10. 11. 12.]] [13. 14. 15.]] [16. 17. 18.]] Two arrays are subtracted from each other: [[-10. -9. -8.]] [ -7. -6. -5.]] [ -4. -3. -2.]] Two arrays are multiplied by each other: [[ 0. 10. 20.]] [30. 40. 50.]] [60. 70. 80.]] Two arrays are divided by each other: [[0. 0.1 0.2] [0.3 0.4 0.5] [0.6 0.7 0.8]]
In addition, Numpy also includes other important arithmetic functions.
The numpy.reciprocal() function returns the reciprocal of each element in the parameter. For example 1/4 Reciprocal is 4/1。
import numpy as np a = np.array([0.25, 1.33, 1, 100]) print ('Our array is:') print(a) print('\n') print ('Call the reciprocal function:') print (np.reciprocal(a))
The output result is:
Our array is: [ 0.25 1.33 1. 100. ] Call the reciprocal function: [4. 0.7518797 1. 0.01 ]
The numpy.power() function takes the elements of the first input array as the base and calculates the power with the corresponding elements in the second input array.
import numpy as np a = np.array([10,100,1000]) print('Our array is;') print(a) print('\n') print('Call the 'power' function:') print(np.power(a,2)) print('\n') print('Second array:') b = np.array([1,2,3] print(b) print('\n') print('Call the 'power' function again:') print(np.power(a,b))
The output result is:
Our array is; [ 10 100 1000] Call the 'power' function: [ 100 10000 1000000] Second array: [1 2 3] Call the 'power' function again: [ 10 10000 1000000000]
numpy.mod() calculates the remainder of the division of corresponding elements in the input array. The function numpy.remainder() also produces the same result.
import numpy as np a = np.array([10,20,30]) b = np.array([3,5,7] print('First array:') print(a) print('\n') print('Second array:') print(b) print('\n') print('Call the 'mod()' function:') print(np.mod(a,b)) print('\n') print('Call the 'remainder()' function:') print(np.remainder(a,b))
First array: [10 20 30] Second array: [3 5 7] Call the 'mod()' function: [1 0 2] Call the 'remainder()' function: [1 0 2]