3 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
如果添加括號(hào),則表達(dá)式有效:
>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'],
dtype='|S1')

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
IMO OP實(shí)際上并不需要np.bitwise_and()(aka &),但實(shí)際上是需要的,np.logical_and()因?yàn)樗鼈冋诒容^邏輯值,例如True和False-請(qǐng)參閱此SO 邏輯與按位比較,以了解區(qū)別。
>>> 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適當(dāng)設(shè)置參數(shù)。
>>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
dtype='|S1')
通過數(shù)字:
>>> %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大致相同。
添加回答
舉報(bào)