NumPy 的通用函数支持向量化操作。
向量化是指对数组执行逐元素操作。在阅读本教程之前,请确保您已理解 向量化。
NumPy 通用函数
NumPy 中的通用函数包括:
- 三角函数,如
sin()
、cos()
和tan()
- 算术函数,如
add()
、subtract()
和multiply()
- 舍入函数,如
floor()
、ceil()
和around()
- 聚合函数,如
mean()
、min()
和max()
。
让我们看一些示例。
示例:三角函数
import numpy as np
# array of angles in radians
angles = np.array([0, 1, 2])
print("Angles:", angles)
# compute the sine of the angles
sine_values = np.sin(angles)
print("Sine values:", sine_values)
# compute the inverse sine of the angles
inverse_sine = np.arcsin(angles)
print("Inverse Sine values:", inverse_sine)
输出
Angles: [0 1 2] Sine values: [0. 0.84147098 0.90929743] Inverse Sine values: [0. 1.57079633 nan]
在此示例中,我们使用通用函数 sin()
和 arcsin()
分别计算正弦和反正弦值。
当我们对数组 angles 执行 sin()
函数时,会对数组的所有元素执行逐元素操作。这称为向量化。
示例:算术函数
import numpy as np
first_array = np.array([1, 3, 5, 7])
second_array = np.array([2, 4, 6, 8])
# using the add() function
result2 = np.add(first_array, second_array)
print("Using the add() function:",result2)
输出
Using the add() function: [ 3 7 11 15]
在此,我们使用通用函数 add()
将两个数组 first_array 和 second_array相加。
示例:舍入函数
import numpy as np
numbers = np.array([1.23456, 2.34567, 3.45678, 4.56789])
# round the array to two decimal places
rounded_array = np.round(numbers, 2)
print("Array after round():", rounded_array)
输出
Array after round(): [1.23 2.35 3.46 4.57]
在此,我们使用通用函数 round()
来舍入数组 numbers 的值。
要了解更多关于三角函数、算术函数和舍入函数的信息,请访问 NumPy 数学函数。
示例:统计函数
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
# calculate the median
median = np.median(array1)
print("Median is:",median)
# find the largest element
max = np.max(array1)
print("Largest element is", max)
输出
Median is: 3.0 Largest element is 5
在此示例中,我们使用通用函数 median()
和 max()
来查找 array1 的中位数和最大元素。
欲了解更多信息,请访问 NumPy 统计函数。