Issue
In numpy, is there a nice idiomatic way of testing if all rows are equal in a 2d array?
I can do something like
np.all([np.array_equal(M[0], M[i]) for i in xrange(1,len(M))])
This seems to mix python lists with numpy arrays which is ugly and presumably also slow.
Is there a nicer/neater way?
Solution
One way is to check that every row of the array arr
is equal to its first row arr[0]
:
(arr == arr[0]).all()
Using equality ==
is fine for integer values, but if arr
contains floating point values you could use np.isclose
instead to check for equality within a given tolerance:
np.isclose(a, a[0]).all()
If your array contains NaN
and you want to avoid the tricky NaN != NaN
issue, you could combine this approach with np.isnan
:
(np.isclose(a, a[0]) | np.isnan(a)).all()
Answered By - Alex Riley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.