python - 在 Python 中从数组中提取特定值

标签 python arrays numpy

我想计算数据集中的均值和平均值,但出于多种原因我无法在此处详述,我的数组包含我的值和一些“填充”值(当前设置为 -1000)。

如何计算非-1000 值的平均值(例如)?

res=[-1000 for x in range(0,10)]
res[1]=2
res[5]=3
res[7]=4
#something like this?
np.mean(res>-1000)

#the result should be the mean value of 2,3 and 4 (3)

MVCE

res=[1.0, 1.0, 1.0, 1.0, 1.0, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000]
#for instance
print(np.mean(res[res > -1000]))

最佳答案

既然你标记了numpy,你应该用它来索引/切片。这是一个例子:

res = np.array([-1000 for x in range(0,10)])
res[1]=2
res[5]=3
res[7]=4

output = np.mean(res[res > -1000])  # 3.0

读取numpy docs有关索引逻辑的更多详细信息。

关于python - 在 Python 中从数组中提取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137367/

相关文章:

c++ - 如何在编译时获取数组大小?

Python 对 np 数组取模

python - Pandas - 如何将字符串列转换为整数...然后转换为 10 个字符的字符串

python - 如何在 python 的 BeautifulSoup4 中使用 .next_sibling 时忽略空行

python - 为什么我的程序无法检测大写字符?

python - Django Rest Framework,查找字段配置不正确

java - 声明数组不工作java

c++ - 在 C++ 中找到给出错误答案的方法

python - numpy.random.seed() 有什么用,有什么区别吗?

python - ND矩阵乘法,无需使用numpy.dot