繁体   English   中英

熊猫在列表列上分组

[英]Pandas groupby on a column of lists

我有一个pandas数据框,其中包含包含lists的列:

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'

一种方法是先转换为元组。 这是因为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM