0

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 :)

5

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.