I want to check if all values in the columns of a numpy array/matrix are the same.
I tried to use reduce of the ufunc equal, but it doesn’t seem to work in all cases:
In [55]: a = np.array([[1,1,0],[1,-1,0],[1,0,0],[1,1,0]])
In [56]: a
Out[56]:
array([[ 1, 1, 0],
[ 1, -1, 0],
[ 1, 0, 0],
[ 1, 1, 0]])
In [57]: np.equal.reduce(a)
Out[57]: array([ True, False, True], dtype=bool)
In [58]: a = np.array([[1,1,0],[1,0,0],[1,0,0],[1,1,0]])
In [59]: a
Out[59]:
array([[1, 1, 0],
[1, 0, 0],
[1, 0, 0],
[1, 1, 0]])
In [60]: np.equal.reduce(a)
Out[60]: array([ True, True, True], dtype=bool)
Why does the middle column in the second case also evaluate to True, while it should be False?
Thanks for any help!
Compare each value to the corresponding value in the first row:
A column shares a common value if all the values in that column are True:
The problem with
np.equal.reducecan be seen by micro-analyzing what happens when it is applied to[1, 0, 0, 1]:The first two items,
1and0are tested for equality and the result isFalse:Now
Falseand0are tested for equality and the result isTrue:But
Trueand 1 are equal, so the total result isTrue, which is not the desired outcome.The problem is that
reducetries to accumulate the result “locally”, while we want a “global” test likenp.all.