Search code examples
pythonnumpyfold

Numpy: Folding an array column-wise


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?


Solution

  • One of possible solutions, using solely Numpy is:

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