计算平均值和第一个标准差之间的平均值

问题描述 投票:0回答:2

我有一个数组:

import numpy as np

# Create an array of values
values = np.array([41,17,44,36,14,29,33,38,49,39,22,15,46])

# Calculate the mean
mean = np.mean(values)

# Calculate the standard deviation
standard_deviation = np.std(values)

如何计算平均值和第一个标准差之间的平均值?我有:

# Calculate the average of values between the mean and the first standard deviation
mean_between_mean_and_first_standard_deviation = np.mean(values[(values >= mean) & (values <= standard_deviation)])
print("Average between mean and first standard deviation:", mean_between_mean_and_first_standard_deviation)

我得到:

Average between mean and first standard deviation: nan

python numpy average mean standard-deviation
2个回答
3
投票

下图应该可以看得更清楚。您需要选择介于

mean
mean
加上
standard_deviation
的一倍之间的值。

np.mean(values[(values >= mean) & (values < (mean + 1 * standard_deviation))])

或者如果你想要中点,你可以这样做:

np.mean([mean, mean + 1 * standard_deviation])


1
投票

例如,您可以这样做:

np.mean(values[np.logical_and(values >= mean, values <= mean+standard_deviation)])

values >= mean
求值为与
values
形状相同的布尔数组,这样在满足条件的地方都有
True
,否则为
False
。同样,对于
values <= mean+standard_deviation
.

剩下的就是使用

np.logical_and()
找到满足这两个条件的地方。然后,仅在值满足两个条件的索引处,使用该布尔数组来计算
values
的平均值

© www.soinside.com 2019 - 2024. All rights reserved.