聚合#

import numpy as np

常用聚合函数#

x = np.random.rand(3, 2)
x
array([[0.42566061, 0.22418217],
       [0.13195343, 0.93749185],
       [0.34686174, 0.94258653]])
# 和值、平均值
np.sum(x), np.mean(x)
(3.008736324074052, 0.501456054012342)
# 最小值、最大值
np.min(x), np.max(x)
(0.13195342800838317, 0.9425865252224497)
# 中位数、百分之20分位数
np.median(x), np.percentile(x, 20)
(0.38626117520318115, 0.22418216952446035)

多维度聚合#

# 行间进行比较,axis=0即行这个维度消失
np.max(x, axis=0)
array([0.42566061, 0.94258653])
y = np.random.randn(2, 3, 4)
y
array([[[-0.69320555, -0.86799502, -2.32735989,  1.6155666 ],
        [ 1.84747356, -0.44785554, -0.01902961,  0.00884816],
        [-1.36638974,  1.58404903,  0.00278553,  1.317238  ]],

       [[ 0.08966157, -0.43411449,  0.75819545,  0.10512166],
        [ 0.4679719 , -0.51876016,  0.82689749,  0.79579887],
        [ 1.48003584,  0.74750487, -0.38781326,  0.86019638]]])
# 另一种写法,axis=1的维度消失
y.sum(axis=1)
array([[-0.21212173,  0.26819847, -2.34360397,  2.94165276],
       [ 2.03766931, -0.20536978,  1.19727968,  1.76111691]])