Reputation: 81
I have a question, which is probably very simple to solve but I just couldn't find an answer. I want to count the number of the values 0, 1 and 2 in the column of a numpy array. My array has two columns, and I want to count the values 0, 1 and 2 in the second column. I tried to solve this like this:
for row in vergleich[:,1]:
n = vergleich[:,1].count(0)
o = vergleich[:,1].count(1)
t = vergleich[:,1].count(2)
print(n)
print(o)
print(t)
But I get the error message : AttributeError: 'numpy.ndarray' object has no attribute 'count' What are other ways to solve this? Thanks in advance :)
Upvotes: 0
Views: 3717
Reputation: 31011
Run: np.count_nonzero(vergleich[:,1] == 0)
, the same for other numbers of interest.
Another, more general alternative:
unique, counts = np.unique(vergleich[:,1], return_counts=True)
result = dict(zip(unique, counts))
Then result will contain key / value pairs:
So then you may query result for keys 0, 1 and 2.
Yet another option, but this time based on Pandas:
Run: res = pd.value_counts(vergleich[:,1])
The result is a Pandas Series with:
Upvotes: 1