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
We can create a function specifically for subtracting the columns, by taking column data as arguments and then using the apply method to apply it to all the data points throughout the column.
subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentially same as doing dataframe – other but with a support to substitute for missing data in one of the inputs.
The sub() method of pandas DataFrame subtracts the elements of one DataFrame from the elements of another DataFrame. Invoking sub() method on a DataFrame object is equivalent to calling the binary subtraction operator(-). The sub() method supports passing a parameter for missing values(np. nan, None).
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
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
for c in ['A','B','C']:
df[c]=df['deposit']-df[c]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With