简体   繁体   中英

How to groupby and transform in pandas

I have dataframe below

A B C
1 1 a
1 2 b       
1 3 c
2 4 d
2 5 e

I would ilke to transform like below

A B C
1 6 a
2 9 d

B means the sum of group and C is the first elements in previous df

How can I get this result ?

It seems you need groupby with aggregation - sum and first :

df = df.groupby('A').agg({'B':'sum','C':'first'}).reset_index().reindex(columns=df.columns)
print (df)
   A  B  C
0  1  6  a
1  2  9  d

Thank you John Galt for another solution:

df = df.groupby('A', as_index=False).agg({'B':'sum','C':'first'}).reindex(columns=df.columns)
print (df)
   A  B  C
0  1  6  a
1  2  9  d

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