11. NumPy 的通用函数 ufunc
NumPy 中的向量化操作可以使数组元素的重复计算更加高效。而向量化操作可以通过通用函数 ufuncs 来实现。
11.1 算术运算
NumPy 的 ufunc 使用起来非常自然,因为它们可以简写为 Python 的原生算术运算符。
ufunc 函数
对应的运算符
含义
np.add
+
加法
np.subtract
-
减法
np.negative
-
一元取负
np.multiply
*
乘法
np.divide
/
除法
np.floor_divide
//
整除
np.power
**
求幂
np.mod
%
取模
import numpy as np
x = np.arange(5)
print("x =", x)
print("x + 5 =", x + 5)
print("x - 5 =", x - 5)
print("x * 2 =", x * 2)
print("x / 2 =", x / 2)
print("x // 2 =", x // 2)
print("-x = ", -x)
print("x ** 2 = ", x ** 2)
print("x % 2 = ", x % 2)
x = [0 1 2 3 4]
x + 5 = [5 6 7 8 9]
x - 5 = [-5 -4 -3 -2 -1]
x * 2 = [0 2 4 6 8]
x / 2 = [0. 0.5 1. 1.5 2. ]
x // 2 = [0 0 1 1 2]
-x = [ 0 -1 -2 -3 -4]
x ** 2 = [ 0 1 4 9 16]
x % 2 = [0 1 0 1 0]
这些运算符也可以组合使用:
print(-(0.5*x + 1) ** 2)
[-1. -2.25 -4. -6.25 -9. ]
11.2 绝对值
ufunc 中取绝对值的函数是 np.absolute, 也可以使用它的别名 np.abs
x = np.array([-1, 0, 1, -2, 2])
np.abs(x)
array([1, 0, 1, 2, 2])
11.3 三角函数
np.sin
np.cos
np.tan
np.arcsin
np.arccos
np.arctan
x = np.array([-1, 0, 1])
np.arccos(x)
array([3.14159265, 1.57079633, 0. ])
11.4 指数和对数
x = np.array([1, 3, 5])
print("x =", x)
print("e^x =", np.exp(x))
print("2^x =", np.exp2(x))
print("3^x =", np.power(3, x))
x = [1 3 5]
e^x = [ 2.71828183 20.08553692 148.4131591 ]
2^x = [ 2. 8. 32.]
3^x = [ 3 27 243]
y = [1, 3, 5]
print("y =", x)
print("ln(y) =", np.log(y))
print("log2(y) =", np.log2(y))
print("log10(y) =", np.log10(y))
y = [1 3 5]
ln(y) = [0. 1.09861229 1.60943791]
log2(y) = [0. 1.5849625 2.32192809]
log10(y) = [0. 0.47712125 0.69897 ]
11.5 通用函数 ufunc 的高级特性
11.5.1 指定输出位置
所有的通用函数都可以通过 out 参数来指定计算结果的存放位置。
x = np.arange(3)
y = np.empty(3)
np.multiply(x, 3, out=y)
print(y)
[0. 3. 6.]
11.5.2 聚合
所有的通用函数都可以通过 reduce 方法来聚合一个数组,即反复对数组的元素应用给定的操作,直到只剩下一个结果。
比如在通用函数 add 上调用 reduce 方法将返回数组中所有元素的总和:
x = np.arange(101)
np.add.reduce(x)
5050
如果要存储计算的所有中间结果,可以使用 accumulate 方法:
np.add.accumulate(x)
array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55,
66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231,
253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528,
561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946,
990, 1035, 1081, 1128, 1176, 1225, 1275, 1326, 1378, 1431, 1485,
1540, 1596, 1653, 1711, 1770, 1830, 1891, 1953, 2016, 2080, 2145,
2211, 2278, 2346, 2415, 2485, 2556, 2628, 2701, 2775, 2850, 2926,
3003, 3081, 3160, 3240, 3321, 3403, 3486, 3570, 3655, 3741, 3828,
3916, 4005, 4095, 4186, 4278, 4371, 4465, 4560, 4656, 4753, 4851,
4950, 5050], dtype=int32)
12. 聚合函数:最小值、最大值及其他
通常在面对大量数据时,第一步就是计算数据集的汇总统计数据。如平均值、标准差以及总和、乘积、中位数、最小值和最大值、分位数等。
NumPy 内置了一系列可以用于快速获取这些值的聚合函数。
12.1 数组求和
x = np.arange(101)
print(sum(x))
print(np.sum(x))
5050
5050
虽然 NumPy 的 sum 函数和 Python 的内建函数 sum 看以来差不多,但它的性能却远超 Python 的内建函数。
bigArray = np.random.rand(1000000)
%timeit sum(bigArray)
%timeit np.sum(bigArray)
248 ms ± 43.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
1.23 ms ± 8.44 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
12.2 最小值和最大值
np.min(bigArray), np.max(bigArray)
(7.071203171893359e-07, 0.9999997207656334)
同样,NumPy 的这两个函数性能也远超 Python 的内建函数。
%timeit min(bigArray)
%timeit np.min(bigArray)
123 ms ± 15.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
921 µs ± 172 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
12.3 其他聚合函数
函数
NaN 安全版本
作用
np.sum
np.nansum
计算总和
np.prod
np.nanprod
计算乘积
np.mean
np.nanmean
计算平均值
np.std
np.nanstd
计算标准差
np.var
np.nanvar
计算方差
np.min
np.nanmin
计算最小值
np.max
np.nanmax
计算最大值
np.argmin
np.nanargmin
获取最小值的序号
np.argmax
np.nanargmax
获取最大值的序号
np.median
np.nanmedian
计算中位数
np.percentile
np.nanpercentile
Compute rank-based statistics of elements
np.any
N/A
判断是否含有为 True 的元素
np.all
N/A
判断是否所有元素都为 True
12.4 使用聚合函数的实例
使用 Pandas 读取文件并提取数据:
import pandas as pd
data = pd.read_csv('data/heights.csv')
heights = np.array(data['height(cm)'])
print(heights)
[189 170 189 163 183 171 185 168 173 183 173 173 175 178 183 193 178 173
174 183 183 168 170 178 182 180 183 178 182 188 175 179 183 193 182 183
177 185 188 188 182 185 190]
print('平均身高:', heights.mean())
print('标准差:', heights.std())
print('最大身高:', heights.max())
print('最小身高:', heights.min())
print('中位数:',np.median(heights))
平均身高: 179.97674418604652
标准差: 7.023178807524852
最大身高: 193
最小身高: 163
中位数: 182.0
%matplotlib inline
import matplotlib.pyplot as plt
plt.hist(heights)
plt.title('Height Distribution')
plt.xlabel('height (cm)')
plt.ylabel('number');