在此 DataFrame 中,我想按“位置”分组并获得“分数”的总和,但我不希望“纬度”、“经度”和“年份”在此过程中受到影响;
sample = pd.DataFrame({'Location':['A','B','C','A','B','C'],
'Year':[2001,2002,2003,2001,2002,2003],
'Lat':[24,32,14,24,32,14],
'Long':[81,85,79,81,85,79],
'Score':[123,234,10,25,46,11]})
grouped = sample.groupby(['Location']).sum().reset_index()
Run Code Online (Sandbox Code Playgroud)
grouped 给我这个;
Location Lat Long Score Year
0 A 48 162 148 4002
1 B 64 170 280 4004
2 C 28 158 21 4006
Run Code Online (Sandbox Code Playgroud)
但我正在寻找这个结果;
Location Lat Long Score Year
0 A 24 81 148 2001
1 B 32 85 280 2002
2 C 12 79 21 2003
Run Code Online (Sandbox Code Playgroud)
您必须为其他列提供某种形式的聚合方法。但是你可以使用mean,first或者last在这种情况下,这一切都可以。
grouped = sample.groupby(['Location']).agg({'Lat': 'first',
'Long': 'first',
'Score': 'sum',
'Year': 'first'}).reset_index()
Run Code Online (Sandbox Code Playgroud)
给出:
Location Score Lat Long Year
0 A 148 24 81 2001
1 B 280 32 85 2002
2 C 21 14 79 2003
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以提供自己的函数,而不是 Pandas 中可以用字符串标识的内置函数。
如果您关心简单的索引,它会弄乱列的顺序:
grouped[['Location', 'Lat', 'Long', 'Score', 'Year']]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
938 次 |
| 最近记录: |