col = full.groupby('state')[['demVote']].mean()
full
是原始表的名称。我如何将这个group by语句的结果作为称为'DEM'
的列附加到原始表中?
答案 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