zaaariina
zaaariina

Reputation: 81

Counting number of specific numbers in the column of a numpy array in python

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

Answers (1)

Valdi_Bo
Valdi_Bo

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:

  • key - value in your column,
  • value - how many times it occurred.

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:

  • index - a value in the source Series (a Numpy 1-D array can also be passed),
  • value - how many times it occurred.

Upvotes: 1

Related Questions