python-3.x - Pandas Series 值包含列表,如何计算唯一值并将其作为字典返回

标签 python-3.x pandas list dictionary

所以我有一个看起来像这样的 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/

相关文章:

python-3.x - 如何使用 pip 获取 python 3.6 的 webbrowser 模块?

python - Pandas 绘图 : How to format datetimeindex?

python - Pandas 为列中的连续值分配累积计数

list - 将多个参数传递给 map 的 func 参数

c++ - 在 C++ 中创建一个具有初始容量的列表

python - 限时输入?

python - 在最后一个元音后查找单词

python - 检索列表列表中元素的索引

python - pandas 将索引值转换为小写

python - 如何替换列表中每个元素中的特定字符