Issue
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!
Solution
In [45]: a
Out[45]:
array([[1, 1, 0],
[1, 0, 0],
[1, 0, 0],
[1, 1, 0]])
Compare each value to the corresponding value in the first row:
In [46]: a == a[0,:]
Out[46]:
array([[ True, True, True],
[ True, False, True],
[ True, False, True],
[ True, True, True]], dtype=bool)
A column shares a common value if all the values in that column are True:
In [47]: np.all(a == a[0,:], axis = 0)
Out[47]: array([ True, False, True], dtype=bool)
The problem with np.equal.reduce
can be seen by micro-analyzing what happens when it is applied to [1, 0, 0, 1]
:
In [49]: np.equal.reduce([1, 0, 0, 1])
Out[50]: True
The first two items, 1
and 0
are tested for equality and the result is False
:
In [51]: np.equal.reduce([False, 0, 1])
Out[51]: True
Now False
and 0
are tested for equality and the result is True
:
In [52]: np.equal.reduce([True, 1])
Out[52]: True
But True
and 1 are equal, so the total result is True
, which is not the desired outcome.
The problem is that reduce
tries to accumulate the result "locally", while we want a "global" test like np.all
.
Answered By - unutbu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.