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

假设我有一个numpy数组x = [5, 2, 3, 1, 4, 5],y = ['f', 'o', 'o', 'b', 'a', 'r']。我要选择与大于1小于5 的元素y相对应的元素x。


我试过了


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']

但这不起作用。我该怎么做?


python numpy的


猛跑小猪
浏览 2475回答 3
3回答

冉冉说

如果添加括号,则表达式有效:>>> y[(1 < x) & (x < 5)]array(['o', 'o', 'a'],&nbsp;&nbsp; &nbsp; &nbsp; dtype='|S1')

GCT1015

IMO OP实际上并不需要np.bitwise_and()(aka &),但实际上是需要的,np.logical_and()因为它们正在比较逻辑值,例如True和False-请参阅此SO 逻辑与按位比较,以了解区别。>>> 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']>>> outputarray(['o', 'o', 'a'],&nbsp; &nbsp; &nbsp; dtype='|S1')同样的方法是np.all()通过axis适当设置参数。>>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a']>>> outputarray(['o', 'o', 'a'],&nbsp; &nbsp; &nbsp; 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大致相同。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python