按列分组求和时忽略部分列
在这个数据表中,我想根据'Location'来分组,然后计算'Score'的总和,但我不希望'Lat'、'Long'和'Year'在这个过程中受到影响。
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()
grouped
给我的结果是这样的;
Location Lat Long Score Year
0 A 48 162 148 4002
1 B 64 170 280 4004
2 C 28 158 21 4006
但我想要的结果是这样的;
Location Lat Long Score Year
0 A 24 81 148 2001
1 B 32 85 280 2002
2 C 12 79 21 2003
1 个回答
8
你需要为其他列提供一种聚合方法。这里可以使用 mean
(平均值)、first
(第一个值)或 last
(最后一个值),这些方法都可以用。
grouped = sample.groupby(['Location']).agg({'Lat': 'first',
'Long': 'first',
'Score': 'sum',
'Year': 'first'}).reset_index()
结果是:
Location Score Lat Long Year
0 A 148 24 81 2001
1 B 280 32 85 2002
2 C 21 14 79 2003
另外,你也可以提供自己的函数,而不是使用Pandas内置的函数,这些函数可以用字符串来识别。
如果你在意列的顺序,使用时要注意,这样可能会打乱列的顺序,你可以通过索引来解决这个问题:
grouped[['Location', 'Lat', 'Long', 'Score', 'Year']]