您可以使用binned_statistic来自 scipy.stats http://scipy.github.io/devdocs/generated/scipy.stats.binned_statistic.html支持将各种统计函数应用于一维数组的块中。为了获取块,我们需要排序并获取移位的位置(块发生变化的位置),其中np.unique http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html会有用的。把所有这些,这是一个实现 -
from scipy.stats import binned_statistic as bstat
# Sort data corresponding to argsort of first column
sdata = data[data[:,0].argsort()]
# Unique col-1 elements and positions of breaks (elements are not identical)
unq_x,breaks = np.unique(sdata[:,0],return_index=True)
breaks = np.append(breaks,data.shape[0])
# Use binned statistic to get grouped average and std deviation values
idx_range = np.arange(data.shape[0])
avg_y,_,_ = bstat(x=idx_range, values=sdata[:,1], statistic='mean', bins=breaks)
std_y,_,_ = bstat(x=idx_range, values=sdata[:,1], statistic='std', bins=breaks)
从文档binned_statistic
,还可以使用自定义统计函数:
function :用户定义的函数,它采用一维值数组,
并输出单个数值统计数据。该函数将被调用
每个 bin 中的值。空垃圾箱将表示为
function([]),如果返回错误则为 NaN。
样本输入、输出 -
In [121]: data
Out[121]:
array([[2, 5],
[2, 2],
[1, 5],
[3, 8],
[0, 8],
[6, 7],
[8, 1],
[2, 5],
[6, 8],
[1, 8]])
In [122]: np.column_stack((unq_x,avg_y,std_y))
Out[122]:
array([[ 0. , 8. , 0. ],
[ 1. , 6.5 , 1.5 ],
[ 2. , 4. , 1.41421356],
[ 3. , 8. , 0. ],
[ 6. , 7.5 , 0.5 ],
[ 8. , 1. , 0. ]])