我有一个数组:
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
例如,您可以这样做:
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
的平均值