本文介绍了如何有条件地选择numpy数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我有条件地选择numpy数组中的元素吗?我正在尝试返回大于阈值的元素.我当前的解决方案是:

Can someone help me with conditionally selecting elements in a numpy array? I am trying to return elements that are greater than a threshold. My current solution is:

sampleArr = np.array([ 0.725, 0.39, 0.99 ])
condition = (sampleArr > 0.5)`
extracted = np.extract(condition, sampleArr) #returns [0.725 0.99]

但是,这似乎是回旋处,我怀疑有一种方法可以做到这一点吗?

However, this seems roundabout and I suspect there's a way to do it in one line?

推荐答案

您可以直接像这样建立索引:

You can index directly like:

sampleArr[sampleArr > 0.5]

测试代码:

sampleArr = np.array([0.725, 0.39, 0.99])

condition = (sampleArr > 0.5)
extracted = np.extract(condition, sampleArr)  # returns [0.725 0.99]

print(sampleArr[sampleArr > 0.5])
print(sampleArr[condition])
print(extracted)

结果:

[ 0.725  0.99 ]
[ 0.725  0.99 ]
[ 0.725  0.99 ]

这篇关于如何有条件地选择numpy数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 23:02