仅获取满足numpy数组中条件的那些值 [英] Getting only those values that fulfill a condition in a numpy array
问题描述
必须有一种(非常)快速有效的方法来从numpy数组中获取元素,或者更有趣的是从它的切片中获取元素. 假设我有一个numpy数组:
There must a be a (very) quick and efficient way to get only elements from a numpy array, or even more interestingly from a slice of it. Suppose I have a numpy array:
import numpy as np
a = np.arange(-10,10)
现在,如果我有一个列表:
Now if I have a list:
s = [9, 12, 13, 14]
我可以从以下元素中选择元素:
I can select elements from a:
a[s] #array([-1, 2, 3, 4])
如何从满足条件的a [s]元素中构成一个(numpy)数组,即是正数(或负数)? 结果应该
How can I have an (numpy) array made of the elements from a[s] that fulfill a condition, i.e. are positive (or negative)? It should result
np.ifcondition(a[s]>0, a[s]) #array([2, 3, 4])
它看起来微不足道,但我无法找到一个简单而简洁的表达方式.我敢肯定,口罩可以,但是对我来说看起来并不是很直接. 但是,都没有:
It looks trivial but I was not able to find a simple and condensed expression. I'm sure masks do but it's doesn't look really direct to me. However, neither:
a[a[s]>0]
a[s[a[s]>0]]
实际上是不错的选择.
推荐答案
怎么样:
In [19]: b = a[s]
In [20]: b[b > 0]
Out[20]: array([2, 3, 4])
这篇关于仅获取满足numpy数组中条件的那些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!