I have many very large padded numpy 2d arrays, simplified to array A, shown below. Array Z is the basic pad array:

A = np.array(([1 , 2, 3], [2, 3, 4], [0, 0, 0], [0, 0, 0], [0, 0, 0])) Z = np.array([0, 0, 0])

How to count the number of pads in array A in the simplest / fastest pythonic way? This works (zCount=3), but seems verbose, loopy and unpythonic:

zCount = 0 for a in A: if a.any() == Z.any(): zCount += 1 zCount

Also tried a one-line list comprehension, which doesn’t work (dont know why not):

[zCount += 1 for a in A if a.any() == Z.any()] zCount

Also tried a list count, but ‘truth value of array with more than one element is ambiguous’:

list(A).count(Z)

Have searched for a simple numpy expression without success. np.count_nonzero gives full elementwise boolean for [0]. Is there a one-word / one-line counting expression for [0, 0, 0]? (My actual arrays are approx. shape (100,30) and I have up to millions of these. I am trying to deal with them in batches, so any simple time savings generating a count would be helpful). thx

## Answer

Try:

>>> np.equal(A, Z).all(axis=1).sum() 3

Step by step:

>>> np.equal(A, Z) array([[False, False, False], [False, False, False], [ True, True, True], [ True, True, True], [ True, True, True]]) >>> np.equal(A, Z).all(axis=1) array([False, False, True, True, True]) >>> np.equal(A, Z).all(axis=1).sum() 3