简体   繁体   English

从Python中的数组中提取特定值

[英]Extract specific values from array in Python

I want to calculate means and averages in a data set, but for many reasons that I can't go into here, my array contains my values and some "filler" values (which are currently set to -1000). 我想计算数据集中的均值和平均值,但由于许多原因(我无法在此处介绍),我的数组包含了我的值和一些“填充物”值(当前设置为-1000)。

How can I calculate the mean (for example) on only the non -1000 values? 如何计算非-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 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]))

Since you tagged numpy , you should use it for indexing / slicing. 由于您标记了numpy ,因此应将其用于索引/切片。 Here's an example: 这是一个例子:

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

Read the numpy docs for more details on indexing logic. 阅读numpy 文档以获取有关索引逻辑的更多详细信息。

Why use another library when you have your friend filter method 有朋友filter方法时,为什么还要使用另一个库

import statistics
number_list = [2, -1000, 3, 4, -1000, -1000]
not_1000 = list(filter(lambda x: x != -1000, number_list))
not_1000_mean = statistics.mean(not_1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM