简体   繁体   中英

Row-wise Logical operation on numpy.ndarray

I have an numpy.ndarray in the following format:

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.]])

and I want to apply the XOR logical operator on elements of each row. ie I want an output like in the following format:

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

How can I do this in Python ? I know about np.logical_xor but I do not know that how I can use it efficiently.

Thanks !!!

Use .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)

Output

[0 1 1 0 0 0]

The function np.logical_xor is an ufunc, as such it has 4 methods , from the documentation (emphasis mine):

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.

To apply an ufunc along an axis use .reduce :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM