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.

Oisin
  • 770
  • 8
  • 22
sara
  • 31
  • 2

3 Answers3

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)

Zachi Shtain
  • 826
  • 1
  • 13
  • 31
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
Dalek
  • 4,168
  • 11
  • 48
  • 100
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 ...   
Akavall
  • 82,592
  • 51
  • 207
  • 251