2

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?

3

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

this does work. it is also O(N^2) . So do not use this for sizeable lists
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.

1 Comment

At least with this small example, collections.Counter is faster.
1

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}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.