1

Lets say i have multiple numpy arrays like this: [1, 2, 4, 7, 1, 4, 6, 8, 1, 8, 2, 5]

I want to count the number of times each item appears in the array, and store the result in a dictionary:

{1: 3, 2: 2, 3: 0, 4: 2, 5: 1, 6: 1, 7: 1, 8: 2}

Is there a faster way to do this than to simply loop over the array and counting the items and storing them in dictionary?

Suraj
  • 2,253
  • 3
  • 17
  • 48

3 Answers3

2

Numpy, in its wisdom, has functionality for this:

np.unique(x, return_counts=True)

It does not return a dictionary, but you can easily convert the result into one.

Igor Rivin
  • 4,632
  • 2
  • 23
  • 35
2

You can do that using count:

MyList = [1, 2, 4, 7, 1, 4, 6, 8, 1, 8, 2, 5]
my_dict = {i:MyList.count(i) for i in MyList}
print(my_dict)

this will definetely work you will find more information here

I think the below one is the easiest way

from collections import Counter
MyList = [1, 2, 4, 7, 1, 4, 6, 8, 1, 8, 2, 5]
print(Counter(MyList))

output would be Counter({1: 3, 2: 2, 4: 2, 8: 2, 7: 1, 6: 1, 5: 1})

Pavan kumar
  • 478
  • 3
  • 16
0

You can do this in pandas

>>> import pandas as pd
>>> a = pd.Series([1, 2, 4, 7, 1, 4, 6, 8, 1, 8, 2, 5])
>>> a.value_counts().to_dict()
{1: 3, 8: 2, 4: 2, 2: 2, 7: 1, 6: 1, 5: 1}
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17