Add or Subract two columns in a dataframe on basis of column?

Zanthoxylum piperitum :

I have df with has three columns name,amount and type. I'm trying to add or subract values to user on basis of type

Here's my sample df

    name    amount  type                  
0   John    10      ADD
1   John    20      ADD
2   John    50      ADD
3   John    50      SUBRACT
4   Adam    15      ADD
5   Adam    25      ADD
6   Adam    5       ADD
7   Adam    30      SUBRACT
8   Mary    100     ADD

My resultant df

    name    amount                    
0   John    30      
1   Adam    15      
2   Mary    100   
jezrael :

Idea is multiple by 1 if ADD and -1 if SUBRACT column and then aggregate sum:

df1 = (df['amount'].mul(df['type'].map({'ADD':1, 'SUBRACT':-1}))
                   .groupby(df['name'], sort=False)
                   .sum()
                   .reset_index(name='amount'))
print (df1)
   name  amount
0  John      30
1  Adam      15
2  Mary     100

Detail:

print (df['type'].map({'ADD':1, 'SUBRACT':-1}))
0    1
1    1
2    1
3   -1
4    1
5    1
6    1
7   -1
8    1
Name: type, dtype: int64

Also is possible specify only negative values with numpy.where for multiple by -1 and all another by 1:

df1 = (df['amount'].mul(np.where(df['type'].eq('SUBRACT'), -1, 1))
                   .groupby(df['name'], sort=False)
                   .sum()
                   .reset_index(name='amount'))
print (df1)

   name  amount
0  John      30
1  Adam      15
2  Mary     100

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360758&siteId=1