Lux*_*_Jr 4 python python-3.x pandas pandas-groupby
我有一个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]
Run Code Online (Sandbox Code Playgroud)
如何组合List列并对列求和Count?预期的结果是:
Count List
5 [once, upon]
6 [a, time]
1 [there, was]
Run Code Online (Sandbox Code Playgroud)
我试过了:
df.groupby('List')['Count'].sum()
Run Code Online (Sandbox Code Playgroud)
这导致:
TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)
一种方法是先转换为元组。这是因为pandas.groupby要求键是可散列的。元组是不可变和可散列的,但列表不是。
res = df.groupby(df['List'].map(tuple))['Count'].sum()
Run Code Online (Sandbox Code Playgroud)
结果:
List
(a, time) 6
(once, upon) 5
(there, was) 1
Name: Count, dtype: int64
Run Code Online (Sandbox Code Playgroud)
如果您需要将结果作为数据框中的列表,您可以转换回来:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4353 次 |
| 最近记录: |