假设我有一个数值数组x = [5, 2, 3, 1, 4, 5]
,y = ['f', 'o', 'o', 'b', 'a', 'r']
。我想选择与x
中大于1和小于5的元素相对应的y
中的元素。
我试过了
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']
但这不管用。我该怎么做呢?
发布于 2010-06-13 08:50:33
如果添加圆括号,则表达式有效:
>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'],
dtype='|S1')
发布于 2013-09-06 03:23:44
IMO OP实际上并不想要np.bitwise_and()
(aka &
),但实际上想要np.logical_and()
,因为它们比较的是逻辑值,例如True
和False
-请参阅logical vs. bitwise上的这篇文章以了解其中的区别。
>>> 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')
实现这一点的等效方法是通过适当设置axis
参数来使用np.all()
。
>>> 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
差不多。
发布于 2014-11-19 00:03:18
在@J.F. Sebastian和@Mark Mikofski的回答中添加一个细节:
如果想要获得相应的索引(而不是数组的实际值),可以使用以下代码:
要满足多个(全部)条件:
select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] # 1 < x <5
用于满足多个(或)条件:
select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5
https://stackoverflow.com/questions/3030480
复制相似问题