Skip to content

Instantly share code, notes, and snippets.

@aarshtalati
Created October 15, 2017 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarshtalati/49d90b3369ea8331ef4df843ad627637 to your computer and use it in GitHub Desktop.
Save aarshtalati/49d90b3369ea8331ef4df843ad627637 to your computer and use it in GitHub Desktop.
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