numpy中的聚合操作
In [1]:
import numpy as np
In [2]:
L = np.random.random(100)
In [4]:
sum(L)
Out[4]:
50.73522038321021
In [9]:
np.sum(L)
Out[9]:
50.73522038321022
In [17]:
big_array = np.random.rand(1000000) # 生成【0, 1)之间均匀分布的随机数组
In [19]:
%%timeit
sum(big_array)
216 ms ± 29.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [20]:
%%timeit
np.sum(big_array)
756 µs ± 29.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [21]:
np.min(big_array)
Out[21]:
2.6997060105227177e-06
In [22]:
np.max(big_array)
Out[22]:
0.9999999906951244
In [23]:
# 面向对象的写法
big_array.min()
Out[23]:
2.6997060105227177e-06
In [24]:
big_array.max()
Out[24]:
0.9999999906951244
In [25]:
big_array.sum()
Out[25]:
500536.93505698355
In [26]:
np.sum(big_array)
Out[26]:
500536.93505698355
多维度聚合操作
In [28]:
X = np.arange(16).reshape(4,-1)
X
Out[28]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
In [30]:
np.sum(X) # 所有元素的和
Out[30]:
120
In [31]:
np.sum(X, axis=0)
Out[31]:
array([24, 28, 32, 36])
In [32]:
np.sum(X, axis=1)
Out[32]:
array([ 6, 22, 38, 54])
In [33]:
# 其他聚合操作
np.prod(X)
Out[33]:
0
In [34]:
np.prod(X+1)
Out[34]:
20922789888000
In [36]:
np.mean(X)# 平均值
Out[36]:
7.5
In [37]:
np.median(X)
Out[37]:
7.5
In [38]:
v = np.array([1,1,2,2,10])
In [39]:
np.mean(v)
Out[39]:
3.2
In [40]:
np.median(v)
Out[40]:
2.0
In [41]:
np.percentile(v,q=50)
Out[41]:
2.0
In [42]:
np.percentile(v,q=100)
Out[42]:
10.0
In [43]:
np.percentile(v,q=25)
Out[43]:
1.0
In [44]:
np.percentile(v,q=75)
Out[44]:
2.0
In [45]:
for percent in [0, 25, 50 ,75, 100]:
print(np.percentile(v, q=percent))
1.0
1.0
2.0
2.0
10.0
In [46]:
np.var(v) # 方差
Out[46]:
11.76
In [47]:
np.std(v) # 标准差
Out[47]:
3.4292856398964493
In [48]:
big_array
Out[48]:
array([0.01825323, 0.09049136, 0.39158914, ..., 0.65815476, 0.27496195,
0.8018582 ])
In [50]:
big_array = np.random.randn(1000000) # 生成均值为0 方差为1 的正太分布数组
np.mean(big_array)
Out[50]:
0.0009935027456538627
In [51]:
np.var(big_array)
Out[51]:
0.9989273366741934
In [52]:
np.std(big_array)
Out[52]:
0.9994635244340803
In [ ]: