Count number of 1's in an array in Python
Question:
I have an array A
. I want to count the number of 1’s in the array but I am getting an error. I present the expected output.
import numpy as np
A=np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0,
0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
B=np.count(A==1)
print(B)
The error is
in __getattr__
raise AttributeError("module {!r} has no attribute "
AttributeError: module 'numpy' has no attribute 'count'
The expected output is
7
Answers:
The np.count
function does not exist, you can use np.count_nonzero
instead.
import numpy as np
A=np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0,
0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
B=np.count_nonzero(A==1) # or just A, if you'll never have anything other than 0 or 1
print(B)
I have an array A
. I want to count the number of 1’s in the array but I am getting an error. I present the expected output.
import numpy as np
A=np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0,
0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
B=np.count(A==1)
print(B)
The error is
in __getattr__
raise AttributeError("module {!r} has no attribute "
AttributeError: module 'numpy' has no attribute 'count'
The expected output is
7
The np.count
function does not exist, you can use np.count_nonzero
instead.
import numpy as np
A=np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0,
0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
B=np.count_nonzero(A==1) # or just A, if you'll never have anything other than 0 or 1
print(B)