Reputation:
So I have a Pandas Series that looks as such
df['LABEL']
0 [0.0]
1 [0.0]
2 [1.0]
3 [3.0]
4 [3.0]
5 [3.0]
I want to count the number of unique values of this Pandas Series, and then return it as a dictionary
However when I use value_count()
it returns an error
Exception ignored in: 'pandas._libs.index.IndexEngine._call_map_locations'
Traceback (most recent call last):
File "pandas\_libs\hashtable_class_helper.pxi", line 1652, in pandas._libs.hashtable.PyObjectHashTable.map_locations
TypeError: unhashable type: 'list'
However after finding the unique values I wish to see it as a dictionary
Expected output would be
{ 0.0 : 2, 1.0: 1, 3.0 : 3}
Upvotes: 2
Views: 468
Reputation: 57105
Assuming all your lists are single-element lists, the following solves your problem:
df['LABEL'].str[0].value_counts().to_dict()
#{3: 3, 0: 2, 1: 1}
If a list has more than one element and you want to count all of them, let the Counter
help:
from collections import Counter
#Replaced the last [3] with [3, 3, 3]
dict(Counter(df['LABEL'].sum()))
#{0: 2, 1: 1, 3: 5}
The latter approach is about 10 times faster than the first one and works for the lists of any length.
Upvotes: 2
Reputation: 17408
In [20]: df
Out[20]:
LABLE
0 [0.0]
1 [0.0]
2 [1.0]
3 [3.0]
4 [3.0]
5 [3.0]
In [19]: df["LABLE"].apply(lambda x: x[0]).value_counts().to_dict()
Out[19]: {3.0: 3, 0.0: 2, 1.0: 1}
Upvotes: 0