1

Here is an array in python:

T = np.array([[1,1,2],[2,1,1],[3,3,3]])

print np.where(T==1)

I want to find the number of appearance of each element. I tried to use np.where and then len(np.where). However the output of np.where doesn't allow to use the len() function.

1
  • was any of these answers useful for your problem? Commented Feb 8, 2016 at 13:36

3 Answers 3

0

You can do as following to show the number of times that the element 1 is repeated in the array T:

>>> (T == 1).sum()
4
>>> (T == 2).sum()
2
Sign up to request clarification or add additional context in comments.

Comments

0

If range of your integers in the array is small you can use np.bincount

In [25]: T = np.array([[1,1,2],[2,1,1],[3,3,3]])

In [26]: np.bincount(T.reshape(-1))
Out[26]: array([0, 4, 2, 3])  # 0 showed up 0 times
                              # 1 showed up 4 times
                              # 2 showed up 2 times ...   

Comments

0

use numpy.unique, it returns both the unique values and the number of appearances in the array. The method has a flag called return_counts which is default value is false like this:

uniqueVals, count = numpy.unique(T, return_counts = true)

3 Comments

numpy.unique will work without reshape, but what parameter do you pass to get the number of appearances?
@Akavall return_counts = true
Ahh. Nice! Maybe you should include that in your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.