简体   繁体   中英

Pandas merge two rows with condition

I wonder if there is a way to groupby rows then conditional aggregate groups. Thank you
for example, for colA is A, it should set colB for second A to test1 and sum colC

colA colB colC
A   test1  5
A   None   6
B   test1  4
C   test1  5
C   test3  4
D   test4  5
D   None   4

expected result

colA colB colC
A   test1  11
B   test1  4
C   test1  5
C   test3  4
D   test4  9

IIUC, You can used groupby and fill and then again group and sum

df['colB'] = df.groupby('colA').colB.ffill().bfill()
df.groupby(['colA','colB'], as_index = False).sum()

    colA    colB    colC
0   A       test1   11
1   B       test1   4
2   C       test1   5
3   C       test3   4
4   D       test4   9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM