在numpy数组中组合逻辑语句AND [英] Combining logic statements AND in numpy array

查看:56
本文介绍了在numpy数组中组合逻辑语句AND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当矩阵中的两个条件为 True 时,选择元素的方法是什么?在 R 中,基本上可以组合布尔值的向量.

What would be the way to select elements when two conditions are True in a matrix? In R, it is basically possible to combine vectors of booleans.

所以我的目标是:

A = np.array([2,2,2,2,2])
A < 3 and A > 1  # A < 3 & A > 1 does not work either

评估为:ValueError:包含多个元素的数组的真值不明确.使用 a.any() 或 a.all()

Evals to: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

它应该评估为:

array([True,True,True,True,True])

我的解决方法通常是将这些布尔向量相加并等于 2,但必须有更好的方法.它是什么?

My workaround usually is to sum these boolean vectors and equate to 2, but there must be a better way. What is it?

推荐答案

你可以只使用 &,例如:

you could just use &, eg:

x = np.arange(10)
(x<8) & (x>2)

给予

array([False, False, False,  True,  True,  True,  True,  True, False, False], dtype=bool)

一些细节:

  • 这是可行的,因为 & 是 numpy ufunc bitwise_and 的简写,对于 bool 类型,它与 logical_and 相同.也就是说,这也可以拼写为
    bitwise_and(less(x,8), Greater(x,2))
  • 您需要括号,因为在 numpy 中 & 的优先级高于 <>
  • and 不起作用,因为它对于 numpy 数组不明确,因此 numpy 引发异常,而不是猜测.
  • This works because & is shorthand for the numpy ufunc bitwise_and, which for the bool type is the same as logical_and. That is, this could also be spelled out as
    bitwise_and(less(x,8), greater(x,2))
  • You need the parentheses because in numpy & has higher precedence than < and >
  • and does not work because it is ambiguous for numpy arrays, so rather than guess, numpy raise the exception.

这篇关于在numpy数组中组合逻辑语句AND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆