numpy数组,如何select满足多个条件的索引?

假设我有一个numpy数组x = [5, 2, 3, 1, 4, 5] 5,2,3,1,4,5 x = [5, 2, 3, 1, 4, 5]y = ['f', 'o', 'o', 'b', 'a', 'r'] 。 我想selecty对应于x中大于1且小于5的元素。

我试过了

 x = array([5, 2, 3, 1, 4, 5]) y = array(['f','o','o','b','a','r']) output = y[x > 1 & x < 5] # desired output is ['o','o','a'] 

但是这不起作用。 我将如何做到这一点?

如果添加括号,则expression式可以工作:

 >>> y[(1 < x) & (x < 5)] array(['o', 'o', 'a'], dtype='|S1') 

国际海事组织OP实际上并不需要np.bitwise_and() (又名& ),但实际上是想要np.logical_and()因为他们正在比较逻辑值,如TrueFalse – 看到这个逻辑与比较后发现差异。

 >>> x = array([5, 2, 3, 1, 4, 5]) >>> y = array(['f','o','o','b','a','r']) >>> output = y[np.logical_and(x > 1, x < 5)] # desired output is ['o','o','a'] >>> output array(['o', 'o', 'a'], dtype='|S1') 

等价的方法是使用np.all()来适当地设置axis参数。

 >>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a'] >>> output array(['o', 'o', 'a'], dtype='|S1') 

由数字:

 >>> %timeit (a < b) & (b < c) The slowest run took 32.97 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 1.15 µs per loop >>> %timeit np.logical_and(a < b, b < c) The slowest run took 32.59 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 1.17 µs per loop >>> %timeit np.all([a < b, b < c], 0) The slowest run took 67.47 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 5.06 µs per loop 

所以使用np.all()比较慢,但是&logical_and大致相同。

给@JF Sebastian's和@Mark Mikofski的答案添加一个细节:
如果你想得到相应的索引(而不是数组的实际值),下面的代码将会执行:

为了满足多个(全部)条件:

 select_indices = np.where( np.logical_and( x > 1, x < 5) ) # 1 < x <5 

为了满足多个(或)条件:

 select_indices = np.where( np.logical_or( x < 1, x > 5 ) ) # x <1 or x >5 

其实我会这样做:

L1是满足条件1的元素的索引列表;(也许你可以使用somelist.index(condition1)np.where(condition1)来获得L1。

同样,你得到L2,满足条件2的元素列表;

然后你使用intersect(L1,L2)find交点。

你也可以find多个列表的交集,如果你有多个条件满足。

然后你可以在任何其他数组中应用索引,例如x。

我喜欢使用np.vectorize来完成这些任务。 考虑以下:

 >>> # Arrays >>> x = np.array([5, 2, 3, 1, 4, 5]) >>> y = np.array(['f','o','o','b','a','r']) >>> # Function containing the constraints >>> func = np.vectorize(lambda t: t>1 and t<5) >>> # Call function on x >>> y[func(x)] >>> array(['o', 'o', 'a'], dtype='<U1') 

优点是可以在向量化函数中添加更多types的约束。

希望能帮助到你。