Skip to main content
 首页 » 编程设计

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

2025年05月04日24hnrainll

我想计算数据集中的均值和平均值,但出于多种原因我无法在此处详述,我的数组包含我的值和一些“填充”值(当前设置为 -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有关索引逻辑的更多详细信息。