gpt4 book ai didi

python - Numpy:评估高于/低于平均值的值的标准差

转载 作者:行者123 更新时间:2023-11-28 22:51:02 26 4
gpt4 key购买 nike

我想计算低于和高于 n_par 参数和 n_sample 样本矩阵平均值的标准偏差。目前我发现最快的方法是:

stdleft = numpy.zeros_like(mean)
for jpar in xrange(mean.shape[1]):
stdleft[jpar] = p[p[:,jpar] < \
mean[jpar],jpar].std()

其中 p 是一个矩阵,如 (n_samples,n_par)。有没有 for 循环的更聪明的方法?我有大约 n_par = 200 和 n_samples = 1e8,因此这三行需要很长时间才能执行。

任何想法都会非常有帮助!

谢谢

最佳答案

据我了解,您想计算每列的标准差,其中的值低于该列的平均值。

在 numpy 中,为此使用掩码数组最简单。

举个例子:

import numpy as np

# 10 samples, 3 columns
p = np.random.random((10, 3))

# Calculate the mean of each column
colmeans = p.mean(axis=0)

# Make a boolean array where our condition is True
mask = p < colmeans

# Find the standard deviation of values in each column below the column's mean.
# For masked arrays, the True values will be masked, so we'll invert the array.
stdleft = np.ma.masked_where(~mask, p).std(axis=0)

您也可以使用 pandas 作为 @SudeepJuvekar 提到的。性能应该大致相似,但对于这个特定操作(未经测试),pandas 应该更快一些。

关于python - Numpy:评估高于/低于平均值的值的标准差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22099246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com