numpy.ndarray 上的按行逻辑运算

Row-wise Logical operation on numpy.ndarray

我有一个 numpy.ndarray 格式如下:

array([[ 0., 0., 0., 0.],
       [ 0., 1., 0., 0.],
       [ 0., 1., 0., 0.],
       ...,
       [ 1.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])

我想对每一行的元素应用 XOR 逻辑运算符。即我想要如下格式的输出:

[[0.],
 [1.],
 [1.],
 ...,
 [1],
 [0],
 [0]]

如何在 Python 中执行此操作?我知道 np.logical_xor 但我不知道如何有效地使用它。

谢谢!!!

使用.reduce:

import numpy as np

arr = np.array([[0., 0., 0., 0.],
                [0., 1., 0., 0.],
                [0., 1., 0., 0.],
                [1., 0., 0., 1.],
                [1., 1., 1., 1.],
                [1., 1., 1., 1.]])

res = np.logical_xor.reduce(arr, 1).astype(np.int32)
print(res)

输出

[0 1 1 0 0 0]

函数 np.logical_xor is an ufunc, as such it has 4 methods,来自文档(强调我的):

All ufuncs have four methods. However, these methods only make sense on scalar ufuncs that take two input arguments and return one output argument. Attempting to call these methods on other ufuncs will cause a ValueError. The reduce-like methods all take an axis keyword, a dtype keyword, and an out keyword, and the arrays must all have dimension >= 1.

要沿轴应用 ufunc,请使用 .reduce:

Reduces array’s dimension by one, by applying ufunc along one axis.