電梯直達(dá):
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 1
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 2
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 3
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 4
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 5
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 6
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 7
Python 科學(xué)計(jì)算庫 NumPy 學(xué)習(xí)筆記 - 8
11. NumPy
的通用函數(shù) ufunc
NumPy
中的向量化操作可以使數(shù)組元素的重復(fù)計(jì)算更加高效郁竟。而向量化操作可以通過通用函數(shù) ufuncs
來實(shí)現(xiàn)懊烤。
11.1 算術(shù)運(yùn)算
NumPy
的 ufunc
使用起來非常自然,因?yàn)樗鼈兛梢院唽憺?Python 的原生算術(shù)運(yùn)算符攒至。
ufunc 函數(shù) |
對(duì)應(yīng)的運(yùn)算符 | 含義 |
---|---|---|
np.add |
+ |
加法 |
np.subtract |
- |
減法 |
np.negative |
- |
一元取負(fù) |
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]
這些運(yùn)算符也可以組合使用:
print(-(0.5*x + 1) ** 2)
[-1. -2.25 -4. -6.25 -9. ]
11.2 絕對(duì)值
ufunc
中取絕對(duì)值的函數(shù)是 np.absolute
, 也可以使用它的別名 np.abs
x = np.array([-1, 0, 1, -2, 2])
np.abs(x)
array([1, 0, 1, 2, 2])
11.3 三角函數(shù)
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 指數(shù)和對(duì)數(shù)
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 通用函數(shù) ufunc
的高級(jí)特性
11.5.1 指定輸出位置
所有的通用函數(shù)都可以通過 out
參數(shù)來指定計(jì)算結(jié)果的存放位置常侣。
x = np.arange(3)
y = np.empty(3)
np.multiply(x, 3, out=y)
print(y)
[0. 3. 6.]
11.5.2 聚合
所有的通用函數(shù)都可以通過 reduce
方法來聚合一個(gè)數(shù)組,即反復(fù)對(duì)數(shù)組的元素應(yīng)用給定的操作,直到只剩下一個(gè)結(jié)果但两。
比如在通用函數(shù) add
上調(diào)用 reduce
方法將返回?cái)?shù)組中所有元素的總和:
x = np.arange(101)
np.add.reduce(x)
5050
如果要存儲(chǔ)計(jì)算的所有中間結(jié)果,可以使用 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. 聚合函數(shù):最小值供置、最大值及其他
通常在面對(duì)大量數(shù)據(jù)時(shí)谨湘,第一步就是計(jì)算數(shù)據(jù)集的匯總統(tǒng)計(jì)數(shù)據(jù)。如平均值、標(biāo)準(zhǔn)差以及總和紧阔、乘積坊罢、中位數(shù)、最小值和最大值擅耽、分位數(shù)等活孩。
NumPy
內(nèi)置了一系列可以用于快速獲取這些值的聚合函數(shù)。
12.1 數(shù)組求和
x = np.arange(101)
print(sum(x))
print(np.sum(x))
5050
5050
雖然 NumPy
的 sum
函數(shù)和 Python 的內(nèi)建函數(shù) sum
看以來差不多乖仇,但它的性能卻遠(yuǎn)超 Python 的內(nèi)建函數(shù)憾儒。
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
的這兩個(gè)函數(shù)性能也遠(yuǎn)超 Python 的內(nèi)建函數(shù)乃沙。
%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 其他聚合函數(shù)
函數(shù) |
NaN 安全版本 |
作用 |
---|---|---|
np.sum |
np.nansum |
計(jì)算總和 |
np.prod |
np.nanprod |
計(jì)算乘積 |
np.mean |
np.nanmean |
計(jì)算平均值 |
np.std |
np.nanstd |
計(jì)算標(biāo)準(zhǔn)差 |
np.var |
np.nanvar |
計(jì)算方差 |
np.min |
np.nanmin |
計(jì)算最小值 |
np.max |
np.nanmax |
計(jì)算最大值 |
np.argmin |
np.nanargmin |
獲取最小值的序號(hào) |
np.argmax |
np.nanargmax |
獲取最大值的序號(hào) |
np.median |
np.nanmedian |
計(jì)算中位數(shù) |
np.percentile |
np.nanpercentile |
Compute rank-based statistics of elements |
np.any |
N/A | 判斷是否含有為 True 的元素 |
np.all |
N/A | 判斷是否所有元素都為 True
|
12.4 使用聚合函數(shù)的實(shí)例
使用 Pandas 讀取文件并提取數(shù)據(jù):
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('標(biāo)準(zhǔn)差:', heights.std())
print('最大身高:', heights.max())
print('最小身高:', heights.min())
print('中位數(shù):',np.median(heights))
平均身高: 179.97674418604652
標(biāo)準(zhǔn)差: 7.023178807524852
最大身高: 193
最小身高: 163
中位數(shù): 182.0
%matplotlib inline
import matplotlib.pyplot as plt
plt.hist(heights)
plt.title('Height Distribution')
plt.xlabel('height (cm)')
plt.ylabel('number');