surya rahul
surya rahul

Reputation: 883

pandas new column on condition

i have a dataframe like this :

 Name    one two 
 John     A   20
 John     P   30
 Alex     B   40
 David    C   50
 Harry    A   60
 Harry    P   40

I want to add those rows where A and P are simultaneously occurring for the specific names such as

 Name  one  two 
 John  A+P 50 
 Alex  B   40  
 David C   50  
 Harry A+P 100   

I tried with sum function of row wise in pandas but didn't got output as in such form needed. Kindly help me out !

Upvotes: 1

Views: 48

Answers (1)

jezrael
jezrael

Reputation: 862601

Use DataFrameGroupBy.agg with join and sum:

df = df.groupby('Name', sort=False, as_index=False).agg({'one':'+'.join, 'two':'sum'})
print (df)
    Name  one  two
0   John  A+P   50
1   Alex    B   40
2  David    C   50
3  Harry  A+P  100

Upvotes: 1

Related Questions