0

I have an n-dimensional boolean numpy array. How can I apply the logical AND operation between each of the columns. I want to get the number of rows that contain only ones.

Example:

n = np.array([[0, 0],
              [1, 0],
              [1, 1],
              [0, 1],
              [1, 0],
              [0, 0],
              [1, 1]]
              )

Here, the result should be 2 because only the third and last row contain only ones.

This can be done via the functools module:

from functools import reduce
np.sum(reduce(np.logical_and, n.T))

but is there a way to do it only with numpy?

2 Answers 2

2

You can use .all(1) to check and on each row then use np.sum() for counting like below:

>>> res = n.all(1)
>>> res
array([False, False,  True, False, False, False,  True])

>>> res.sum()
2
Sign up to request clarification or add additional context in comments.

Comments

1

One of possible solutions, using solely Numpy is:

np.sum(np.equal(n, 1).all(axis=1))

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.