所以我有一个看起来像这样的 Pandas 系列
df['标签']
0 [0.0]
1 [0.0]
2 [1.0]
3 [3.0]
4 [3.0]
5 [3.0]
我想计算这个 Pandas Series 的唯一值的数量,然后将其作为字典返回
但是,当我使用 value_count()
时,它会返回错误
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'
但是在找到唯一值之后,我希望将其视为字典
预期输出为
{ 0.0 : 2, 1.0: 1, 3.0 : 3}
最佳答案
假设您的所有列表都是单元素列表,以下内容可以解决您的问题:
df['LABEL'].str[0].value_counts().to_dict()
#{3: 3, 0: 2, 1: 1}
如果列表包含多个元素,并且您想要对所有元素进行计数,请使用计数器
来帮助:
from collections import Counter
#Replaced the last [3] with [3, 3, 3]
dict(Counter(df['LABEL'].sum()))
#{0: 2, 1: 1, 3: 5}
后一种方法比第一种方法快大约 10 倍,并且适用于任何长度的列表。
关于python-3.x - Pandas Series 值包含列表,如何计算唯一值并将其作为字典返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63026545/