Reputation: 4624
How can I dynamically subtract values in multiple pandas dataframe columns from a specified column. In this case, how can I subtract columns A, B, and C from deposit and place the value in the corresponding A, B, and C columns.
date deposit A B C
0 2017-01-15 12 5 10 12
1 2017-01-16 20 10 4 32
2 2017-01-17 5 50 10 18
3 2017-01-18 22 15 20 12
should produce:
date deposit A B C
0 2017-01-15 12 7 2 0
1 2017-01-16 20 10 16 -12
2 2017-01-17 5 -45 -5 -13
3 2017-01-18 22 7 2 10
Upvotes: 7
Views: 5177
Reputation: 294506
loc
+ rsub
cols = ['A', 'B', 'C']
df.loc[:, cols] = df[cols].rsub(df.deposit, 0)
df
date deposit A B C
0 2017-01-15 12 7 2 0
1 2017-01-16 20 10 16 -12
2 2017-01-17 5 -45 -5 -13
3 2017-01-18 22 7 2 10
inplace
My preference for doing it inplace
df.update(df[['A', 'B', 'C']].rsub(df.deposit, 0))
df
date deposit A B C
0 2017-01-15 12 7 2 0
1 2017-01-16 20 10 16 -12
2 2017-01-17 5 -45 -5 -13
3 2017-01-18 22 7 2 10
copy
My preference overall
df.assign(**df[['A', 'B', 'C']].rsub(df.deposit, 0).to_dict('list'))
date deposit A B C
0 2017-01-15 12 7 2 0
1 2017-01-16 20 10 16 -12
2 2017-01-17 5 -45 -5 -13
3 2017-01-18 22 7 2 10
Upvotes: 5
Reputation: 210942
In [226]: df[['A','B','C']] = df.deposit.values[:, None] - df[['A','B','C']]
In [227]: df
Out[227]:
date deposit A B C
0 2017-01-15 12 7 2 0
1 2017-01-16 20 10 16 -12
2 2017-01-17 5 -45 -5 -13
3 2017-01-18 22 7 2 10
Upvotes: 6