One simple way: broadcasting -
(array_2d == row).all(-1).sum()
Considering memory efficiency, there is seen one approach, examining each line of array_2d as the indexing set in a grid n-dimensional , and assuming the inputs are positive numbers -
dims = np.maximum(array_2d.max(0),row) + 1 array_1d = np.ravel_multi_index(array_2d.T,dims) row_scalar = np.ravel_multi_index(row,dims) count = (array_1d==row_scalar).sum()
Here, a message dedicated to the various aspects associated with it.
Note. Using np.count_nonzero may be much faster to calculate Boolean summation elements instead via .sum() . So, think about using it for both of the above aprobashey.
Here's a quick test execution time -
In [74]: arr = np.random.rand(10000)>0.5 In [75]: %timeit arr.sum() 10000 loops, best of 3: 29.6 ยตs per loop In [76]: %timeit np.count_nonzero(arr) 1000000 loops, best of 3: 1.21 ยตs per loop
source share