我有一组数据 (X,Y)。我的自变量值 X 不是唯一的,所以有多个重复值,我想输出一个新数组,其中包含: X_unique,这是 X 的唯一值列表。 Y_mean,与 X_unique 对应的所有 Y 值的平均值. Y_std,X_unique对应的所有Y值的标准差。
x = data[:,0]
y = data[:,1]
最佳答案
您可以使用 binned_statistic
from scipy.stats支持在一维数组中以 block 的形式应用各种统计函数。为了获得 block ,我们需要排序并获取移位的位置( block 发生变化的位置),为此 np.unique
会有用的。把所有这些,这里是一个实现 -
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 : a user-defined function which takes a 1D array of values, and outputs a single numerical statistic. This function will be called on the values in each bin. Empty bins will be represented by function([]), or NaN if this returns an error.
示例输入、输出-
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. ]])
关于python - 使用 NumPy 数组执行分组平均值和标准差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34617608/