我正在尝试用大熊猫每月付款来模拟贷款.
在信用列包含这是我从银行借款的金额.
该借记列包含我祈祷,回到银行的钱数.
该总列应该包含哪些被留下支付给银行的金额.基本上它包含信用和借记列之间的减法结果).
我能够编写以下代码:
import pandas as pd
# This function returns the subtraction result of credit and debit
def f(x):
return (x['credit'] - x['debit'])
df = pd.DataFrame({'credit': [1000, 0, 0, 500],
'debit': [0, 100, 200, 0]})
for i in df:
df['total'] = df.apply(f, axis=1)
print(df)
Run Code Online (Sandbox Code Playgroud)
它有效(它从信用卡中扣除借方).但它不会在总列中保留结果.请参阅下面的实际和预期结果.
实际结果:
credit debit total
0 1000 0 1000
1 0 100 -100
2 0 200 -200
3 500 0 500
Run Code Online (Sandbox Code Playgroud)
预期结果:
credit debit total
0 1000 0 1000
1 0 100 900
2 0 200 700
3 500 0 1200
Run Code Online (Sandbox Code Playgroud)
你可以使用cumsum:
df['total'] = (df.credit - df.debit).cumsum()
print(df)
Run Code Online (Sandbox Code Playgroud)
产量
credit debit total
0 1000 0 1000
1 0 100 900
2 0 200 700
3 500 0 1200
Run Code Online (Sandbox Code Playgroud)