Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Numpy count elements
import numpy as np
x = np.arange(20).reshape(4,5)
y = x % 3 == 0
y = y.astype(int) # optional, if dealing with only 1s and 0s
# simple
np.count_nonzero(y == 1) # 7
np.count_nonzero(y == 0) # 13
(y == 1).sum() # 7
(y == 0).sum() # 13
# slightly complex
np.count_nonzero(x > 5) # 14
(x > 9).sum() # 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment