更新时间:2022-12-11 20:07:05
一种方法是先转换为元组.这是因为 pandas.groupby
要求键是可散列的.元组是不可变和可散列的,但列表不是.
One way is to convert to tuples first. This is because pandas.groupby
requires keys to be hashable. Tuples are immutable and hashable, but lists are not.
res = df.groupby(df['List'].map(tuple))['Count'].sum()
结果:
List
(a, time) 6
(once, upon) 5
(there, was) 1
Name: Count, dtype: int64
如果您需要数据帧中的列表形式的结果,您可以转换回来:
If you need the result as lists in a dataframe, you can convert back:
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