Home > database >  Numpy: Folding an array column-wise
Numpy: Folding an array column-wise

Time:11-01

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?

CodePudding user response:

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

CodePudding user response:

One of possible solutions, using solely Numpy is:

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