[英]How to add/subtract row values from each other in pandas?
I have a DataFrame that looks like:我有一个 DataFrame,看起来像:
credit debit
0 0.0 89.40
1 0.0 4.33
2 0.0 12.00
3 500.0 0.00
4 0.0 5.40
If I know the current balance is 300, how do I make a balance column that subtracts the debit from each row and adds the credit from each row?如果我知道当前余额是 300,我如何制作一个余额列,从每一行中减去借方并从每一行中添加贷方?
I have tried using df.sub
but I am having no luck...我试过使用
df.sub
但我没有运气......
The Balance column should look like:余额列应如下所示:
balance
300.00
389.40
393.33
405.33
-94.27
here is the code for the sample DataFrame这是示例 DataFrame 的代码
df = pd.DataFrame({'credit': {0: 0.0, 1: 0.0, 2: 0.0, 3: 500.0, 4: 0.0},'debit': {0: 89.4, 1: 4.33, 2: 12.0, 3: 0.0, 4: 5.4}})
Like this:像这样:
In [511]: df['balance'] = df.debit.cumsum() + 300 - df.credit.cumsum()
In [512]: df
Out[512]:
credit debit balance
0 0.0 89.40 389.40
1 0.0 4.33 393.73
2 0.0 12.00 405.73
3 500.0 0.00 -94.27
4 0.0 5.40 -88.87
OR:要么:
In [513]: df['balance'] = df.debit.cumsum().sub(df.credit.cumsum()).add(300)
I am thinking that you are looking for a "running balance" of the dataframe. If yes, continue to read else discard.我认为您正在寻找 dataframe 的“运行余额”。如果是,请继续阅读,否则请丢弃。
import pandas as pd
from itertools import accumulate
import operator
import numpy as np
DF = pd.DataFrame({'credit': {0: 0.0, 1: 0.0, 2: 0.0, 3: 500.0, 4: 0.0},
'debit': {0: 89.4, 1: 4.33, 2: 12.0, 3: 0.0, 4: 5.4}})
Initial_Balance = 300
Running_Balance = np.array(list(accumulate(DF.debit-DF.credit, func=operator.add)))+Initial_Balance
DF["Running_Balance"] = Running_Balance
print(DF)
This gives the following output.这给出以下 output。
credit debit Running_Balance
0 0.0 89.40 389.40
1 0.0 4.33 393.73
2 0.0 12.00 405.73
3 500.0 0.00 -94.27
4 0.0 5.40 -88.87
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.