在 Pandas 中,按照一个列进行分组(groupby()),然后对另一个列求和(sum)。

9

我有一个数据框,其中有许多列,但我只对三列感兴趣。它们是nameyeargoals_scored。这些列都不是唯一的,例如我有以下行:

Name           Year     Goals_scored
John Smith     2014     3
John Smith     2014     2
John Smith     2014     0
John Smith     2015     1
John Smith     2015     1
John Smith     2015     2
John Smith     2015     1
John Smith     2015     0
John Smith     2016     1
John Smith     2016     0

我尝试创建一个新的数据框,其中包含4列。一列是名字,然后是2014年、2015年和2016年的每一年各一列。最后三列是该年份进球数的总和。所以使用上面的数据看起来像这样:
Name          2014     2015     2016
John Smith    5        5        1

为了让情况更糟糕,他们只想要包括那些在三年内都有相关内容的名称。请问有人能指点我吗?
1个回答

13
需要使用 groupby,通过 sum 进行聚合,并使用 unstack 进行重塑:
df = df.groupby(['Name','Year'])['Goals_scored'].sum().unstack()
print (df)
Year        2014  2015  2016
Name                        
John Smith     5     5     1

替代方案 pivot_table

df = df.pivot_table(index='Name',columns='Year', values='Goals_scored', aggfunc='sum')
print (df)
Year        2014  2015  2016
Name                        
John Smith     5     5     1

从索引开始往后的最后一列:

df = df.reset_index().rename_axis(None, 1)
print (df)
         Name  2014  2015  2016
0  John Smith     5     5     1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接