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. i.e. 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 !!!
CodePudding user response:
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.