Pandas按列表列分组

11

我有一个包含list的列的pandas数据框:

df = pd.DataFrame({'List': [['once', 'upon'], ['once', 'upon'], ['a', 'time'], ['there', 'was'], ['a', 'time']], 'Count': [2, 3, 4, 1, 2]})

Count   List
2    [once, upon]
3    [once, upon]
4    [a, time]
1    [there, was]
2    [a, time]

我该如何合并List列并求和Count列?预期结果是:
Count   List
5     [once, upon]
6     [a, time]
1     [there, was]

我曾尝试过:
df.groupby('List')['Count'].sum()

这将导致:
TypeError: unhashable type: 'list'
1个回答

14

一种方法是先转换为元组。这是因为 pandas.groupby 要求键必须是可哈希的。元组是不可变且可哈希的,而列表则不是。

res = df.groupby(df['List'].map(tuple))['Count'].sum()

结果:

List
(a, time)       6
(once, upon)    5
(there, was)    1
Name: Count, dtype: int64

如果您需要将结果以列表的形式呈现在数据框中,您可以进行转换:

res = df.groupby(df['List'].map(tuple))['Count'].sum()
res['List'] = res['List'].map(list)

#            List  Count
# 0     [a, time]      6
# 1  [once, upon]      5
# 2  [there, was]      1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接