Subtract pandas columns from specified column
How to dynamically subtract values โโin pandas dataframe columns from specified column:
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
subtract columns not related to date or deposit (i.e. A, B, C) from the deposit in different ways:
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
+3
source to share
3 answers
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 this 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 preferences in general
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
+2
source to share