python中用于2D数组的元素级AND或or操作
python中是否有任何方法可以跨行或跨列计算二维数组的elementwise OR运算 例如,对于以下数组,跨行的elementwise或操作将导致向量python中用于2D数组的元素级AND或or操作,python,numpy,logical-operators,Python,Numpy,Logical Operators,python中是否有任何方法可以跨行或跨列计算二维数组的elementwise OR运算 例如,对于以下数组,跨行的elementwise或操作将导致向量[1,0,0,0,0,0,0] array([[1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) numpy有logi
[1,0,0,0,0,0,0]
array([[1, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
numpy有
logical\u或
,logical\u异或
和logical\u和
,它们有一个减少
方法
>> np.logical_or.reduce(a, axis=0)
array([ True, False, False, False, False, False, False, False], dtype=bool)
正如您在示例中看到的,它们强制执行bool
dtype,因此如果您需要uint8
,那么最后必须回退
因为bool存储为字节,所以可以使用廉价的viewcasting
使用轴
关键字,您可以选择沿哪个轴减小。可以选择多个轴
>> np.logical_or.reduce(a, axis=1)
array([ True, True, True, True], dtype=bool)
>>> np.logical_or.reduce(a, axis=(0, 1))
True
keepdims
关键字对于广播非常有用,例如在数组b
>>> b = np.random.randint(0,10, (4, 4))
>>> b
array([[0, 5, 3, 4],
[4, 1, 5, 4],
[4, 5, 5, 5],
[2, 4, 6, 1]])
>>> rows = np.logical_and.reduce(b >= 2, axis=1, keepdims=True)
# keepdims=False (default) -> rows.shape==(4,) keepdims=True -> rows.shape==(4, 1)
>>> cols = np.logical_and.reduce(b >= 2, axis=0, keepdims=True)
# keepdims=False (default) -> cols.shape==(4,) keepdims=True -> cols.shape==(1, 4)
>>> rows & cols # shapes (4, 1) and (1, 4) are broadcast to (4, 4)
array([[False, False, False, False],
[False, False, False, False],
[False, False, True, False],
[False, False, False, False]], dtype=bool)
请注意,和
运算符有轻微的滥用,它表示按位_和
。由于bools的效果是相同的(事实上,在这里尝试使用和会引发异常),这是常见的做法
正如@ajcr指出的,流行的np.any
和np.all
都是np.logical\u或.reduce
和np.logical\u和.reduce的缩写。
然而,请注意,两者之间存在细微的差异
>>> np.logical_or.reduce(a)
array([ True, False, False, False, False, False, False, False], dtype=bool)
>>> np.any(a)
True
或:
如果您想坚持使用uint8
并确定所有条目都是0和1,您可以使用bitwise\u和
、bitwise\u或
和bitwise\u异或
>>> np.bitwise_or.reduce(a, axis=0)
array([1, 0, 0, 0, 0, 0, 0, 0], dtype=uint8)
是:请特别参阅ufuncs的.reduce
方法的详细信息。您可以使用numpy.apply_沿_轴()
对于OP的特定和
/或
情况,可能还值得注意的是logical_或.reduce
仅等同于np.any
或ndarray.any
,并且logical_和.reduce
与np.all
或ndarray.all
完全相同(这是在中定义它们的方式)。