且构网

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

按一列分组,然后在 pandas 中查找另一列的总和和最大值

更新时间:2022-11-14 12:08:55

您可以使用groupby / transform创建所需的列

You can use groupby/transform to creat the required columns

df[['col1_sum', 'col4_sum']]=df.groupby('id')['col1', 'cl4'].transform('sum')
df[['col2_max', 'col3_max']]=df.groupby('id')['col1', 'cl4'].transform('max')

    Name    id  col1    col2    col3    cl4 col1_sum    col4_sum    col2_max    col3_max
0   PL      252 0       747     3       53  5           101         4   53
1   PL2     252 1       24      2       35  5           101         4   53
2   PL3     252 4       75      24      13  5           101         4   53
3   AD      889 53      24      0       95  76          114         53  95
4   AD2     889 23      2       0       13  76          114         53  95
5   AD3     889 0       24      3       6   76          114         53  95
6   BG      24  12      89      53      66  60          70          43  66
7   BG1     24  43      16      13      0   60          70          43  66
8   BG2     24  5       32      101     4   60          70          43  66