python - 使用 NumPy 数组执行分组平均值和标准差

标签 python arrays numpy

我有一组数据 (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/

相关文章:

python - 最小化加载多对多关系的性能问题

python - lxml 无法解析 <table>?

vb.net - 不要使用数组列表!

java - 修剪字节数组末尾的空元素 - Java

python - 如何在 numpy 中创建子矩阵

python - 按特定列对矩阵进行排序(具有 2 位或更多数字)

python - Python中的多元线性回归

python - 如何将 int 映射到 redis 中的列表?

python - 路由到基于字符串的方法

javascript - 将标记从数组添加到带有图层支持的传单中的标记簇中