Python Numpy数组的操作
NumPy是一个Python包,意思是 “Numerical Python”。它是逻辑计算的库,它包含一个强大的n维数组对象,给出了整合C、C++等的工具。它在基于线性的数学、任意数能力等方面也同样有帮助。NumPy的展品同样可以作为通用数据的有效多维隔间来利用。NumPy数组。Numpy数组是一个强大的N维数组对象,它是以行和列的形式存在。我们可以从嵌套的Python列表中初始化NumPy数组并访问其元素。一个Numpy数组在结构层面上是由以下元素的组合组成的。
- 数据指针表示阵列中第一个字节的内存地址。
- 数据类型或dtype指针描述了包含在数组中的元素的种类。
- 形状表示阵列的形状。
- 跨度是指在内存中跳过的字节数,以进入下一个元素。
对Numpy数组的操作
算术操作:
# Python code to perform arithmetic
# operations on NumPy array
import numpy as np
# Initializing the array
arr1 = np.arange(4, dtype = np.float_).reshape(2, 2)
print('First array:')
print(arr1)
print('\nSecond array:')
arr2 = np.array([12, 12])
print(arr2)
print('\nAdding the two arrays:')
print(np.add(arr1, arr2))
print('\nSubtracting the two arrays:')
print(np.subtract(arr1, arr2))
print('\nMultiplying the two arrays:')
print(np.multiply(arr1, arr2))
print('\nDividing the two arrays:')
print(np.divide(arr1, arr2))
输出:
First array:
[[ 0. 1.]
[ 2. 3.]]
Second array:
[12 12]
Adding the two arrays:
[[ 12. 13.]
[ 14. 15.]]
Subtracting the two arrays:
[[-12. -11.]
[-10. -9.]]
Multiplying the two arrays:
[[ 0. 12.]
[ 24. 36.]]
Dividing the two arrays:
[[ 0. 0.08333333]
[ 0.16666667 0.25 ]]
numpy.reciprocal() 该函数返回参数的倒数,按元素排列。对于绝对值大于1的元素,其结果总是0,对于整数0,会发出溢出警告。例子:
# Python code to perform reciprocal operation
# on NumPy array
import numpy as np
arr = np.array([25, 1.33, 1, 1, 100])
print('Our array is:')
print(arr)
print('\nAfter applying reciprocal function:')
print(np.reciprocal(arr))
arr2 = np.array([25], dtype = int)
print('\nThe second array is:')
print(arr2)
print('\nAfter applying reciprocal function:')
print(np.reciprocal(arr2))
输出
Our array is:
[ 25. 1.33 1. 1. 100. ]
After applying reciprocal function:
[ 0.04 0.7518797 1. 1. 0.01 ]
The second array is:
[25]
After applying reciprocal function:
[0]
numpy.power()该函数将第一个输入数组中的元素视为基数,并返回其升至第二个输入数组中相应元素的幂。
# Python code to perform power operation
# on NumPy array
import numpy as np
arr = np.array([5, 10, 15])
print('First array is:')
print(arr)
print('\nApplying power function:')
print(np.power(arr, 2))
print('\nSecond array is:')
arr1 = np.array([1, 2, 3])
print(arr1)
print('\nApplying power function again:')
print(np.power(arr, arr1))
输出:
First array is:
[ 5 10 15]
Applying power function:
[ 25 100 225]
Second array is:
[1 2 3]
Applying power function again:
[ 5 100 3375]
numpy.mod()该函数返回输入数组中相应元素的除法余数。函数numpy.remainder()也产生相同的结果。
# Python code to perform mod function
# on NumPy array
import numpy as np
arr = np.array([5, 15, 20])
arr1 = np.array([2, 5, 9])
print('First array:')
print(arr)
print('\nSecond array:')
print(arr1)
print('\nApplying mod() function:')
print(np.mod(arr, arr1))
print('\nApplying remainder() function:')
print(np.remainder(arr, arr1))
输出:
First array:
[ 5 15 20]
Second array:
[2 5 9]
Applying mod() function:
[1 0 2]
Applying remainder() function:
[1 0 2]