Home > Back-end >  Numpy check that all the element of each row of a 2D numpy array is the same
Numpy check that all the element of each row of a 2D numpy array is the same

Time:11-17

I am sure this is an already answered question, but I couldn't find anywhere.

I want to check that all the element of each row of a 2D numpy array is the same and 0 is a possibility.

For example:

>>> a = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]])
>>> a
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])
>>> function_to_find(a)
True

Looking around there are suggestions to use all() and any(), but I don't think it's my case.

If I use them in this way:

>>> a = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]])
>>> a.all()
False
>>> a.all(axis=1)
array([False,  True,  True,  True])
>>> a.all(axis=1).any()
True

but also this give me True and I want False:

>>> a = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 5]])
>>> a.all()
False
>>> a.all(axis=1)
array([False,  True,  True,  True])
>>> a.all(axis=1).any()
True

A solution could be:

results_bool = np.array([])

for i in a:
    results_bool = np.append(results_bool, np.all(i == i[0]))

result = np.all(results_bool)

but I would prefer to avoid loops and use numpy.

Any idea?

CodePudding user response:

You can simply do the following:

result = (a[:, 1:] == a[:, :-1]).all()

Or, with broadcasting:

result = (a[:, 1:] == a[:, [0]]).all()

result = (a == a[:, [0]]).all() is similar, but the above avoids the redundant comparison of the column a[:,0] to itself.

  • Related