0

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?

1
  • 1
    (a==a[:,[0]]).all() can be an option Commented Nov 16, 2022 at 17:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.