Heisenberg
Heisenberg

Reputation: 5279

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 ?

Upvotes: 2

Views: 97

Answers (1)

jezrael
jezrael

Reputation: 862396

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

Upvotes: 2

Related Questions