Numpy数组,如何选择满足多个条件的指数?

Bob*_*Bob 126 python numpy

假设我有一个numpy数组x = [5, 2, 3, 1, 4, 5],y = ['f', 'o', 'o', 'b', 'a', 'r'].我想选择y对应于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']
Run Code Online (Sandbox Code Playgroud)

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

jfs*_*jfs 189

如果添加括号,则表达式有效:

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

  • @JennyYueJin:因为优先权而发生.(按位)`&`的优先级高于`<`和`>`,后者的优先级高于(逻辑)`和`.`x> 1和x <5`首先检验不等式,然后是逻辑连词; `x> 1&x <5`评估`1`和(x)中的值的按位连接,然后是不等式.`(x> 1)&(x <5)`强制不等式首先进行评估,因此所有操作都按预期顺序发生,结果都是明确定义的.[参见此处的文档.](https://docs.python.org/3/reference/expressions.html#operator-precedence) (6认同)

Mar*_*ski 31

IMO OP实际上并不想要np.bitwise_and()(又名&)但实际上想要,np.logical_and()因为他们正在比较逻辑值,例如TrueFalse- 请参阅逻辑与按位的 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']
>>> output
array(['o', 'o', 'a'],
      dtype='|S1')
Run Code Online (Sandbox Code Playgroud)

这样做的等效方法是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')
Run Code Online (Sandbox Code Playgroud)

按数字:

>>> %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
Run Code Online (Sandbox Code Playgroud)

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

  • 对于布尔数组,bitwise_and()和logical_and()之间没有区别 (15认同)
  • 您需要对如何评价所评估的内容进行一些小心谨慎.例如,在`output = y [np.logical_and(x> 1,x <5)]`中,`x <5`*被*评估(可能创建一个巨大的数组),即使它是第二个参数,因为评估发生在函数之外.IOW,`logical_and`传递了两个已经评估过的参数.这与"a和b"的通常情况不同,其中如果"a"是真实的,则不评估"b". (7认同)

Goo*_*ill 19

在@JF Sebastian和@Mark Mikofski的答案中添加一个细节:
如果想要获得相应的索引(而不是数组的实际值),以下代码将执行:

为了满足多个(所有)条件:

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5
Run Code Online (Sandbox Code Playgroud)

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

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5
Run Code Online (Sandbox Code Playgroud)

  • 请注意, numpy.where 不仅会返回一个索引数组,还会返回一个包含数组的元组(condition.nonzero() 的输出) - 在这种情况下,`(你想要的索引数组,)`,所以你需要 `select_indices = np.where(...)[0]` 来获得你想要和期望的结果。 (2认同)

小智 5

我喜欢用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')
Run Code Online (Sandbox Code Playgroud)

优点是您可以在矢量化函数中添加更多类型的约束.

希望能帮助到你.