我有一个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
如果我知道当前余额为300,我该如何创建一个余额列,该列从每一行中减去借方并在每一行中添加贷方?
我尝试使用,df.sub
但是我没有运气...
余额列应如下所示:
balance
300.00
389.40
393.33
405.33
-94.27
这是示例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}})
我认为您正在寻找数据框的“运行平衡”。如果是,请继续阅读,否则丢弃。
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)
这给出以下输出。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句