Python 在一列列表上按分组
我有一个Python 在一列列表上按分组,python,python-3.x,pandas,pandas-groupby,Python,Python 3.x,Pandas,Pandas Groupby,我有一个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
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]
如何组合列表
列并对计数
列求和?预期结果是:
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