且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pandas 将列添加到groupby数据框

更新时间:2023-12-03 08:05:40

使用 transform 将列从groupby聚合添加回orig df,transform返回其索引与orig df对齐的Series:

Use transform to add a column back to the orig df from a groupby aggregation, transform returns a Series with its index aligned to the orig df:

In [123]:
g = df.groupby('c')['type'].value_counts().reset_index(name='t')
g['size'] = df.groupby('c')['type'].transform('size')
g

Out[123]:
   c type  t  size
0  1    m  1     3
1  1    n  1     3
2  1    o  1     3
3  2    m  2     4
4  2    n  2     4