将GROUP BY结果附加到原始表中

时间:2018-09-04 22:16:05

标签: python pandas

 col = full.groupby('state')[['demVote']].mean()

full是原始表的名称。我如何将这个group by语句的结果作为称为'DEM'的列附加到原始表中?

2 个答案:

答案 0 :(得分:0)

我认为这可以解决问题,如果不能,请提供具体示例?

full['DEM'] = full.groupby('state').mean()['demVote']

答案 1 :(得分:0)

使用transform

full['DEM'] = full.groupby('state')['demVote'].transform('mean')

例如:

>>> full
   demVote state
0        1    ca
1        2    ca
2        3    ny
3        4    ny

full['DEM'] = full.groupby('state')['demVote'].transform('mean')

>>> full
   demVote state  DEM
0        1    ca  1.5
1        2    ca  1.5
2        3    ny  3.5
3        4    ny  3.5