Skip to main content
 首页 » 编程设计

python之对 Pandas 数据框使用应用函数

2025年05月04日12yjmyzz

<分区>

我正在尝试模拟使用 pandas 每月支付的贷款。

credit 列包含我从银行借来的金额。

借方列包含我还给银行的金额。

total 列应包含要支付给银行的剩余金额。基本上它包含贷方和借方列之间的减法结果。

我能够编写以下代码:

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) 

它有效(它从贷方中减去借方)。但它不会将结果保留在总计列中。请参阅下面的实际和预期结果。

实际结果:

   credit  debit        total 
0    1000      0         1000 
1       0    100         -100 
2       0    200         -200 
3     500      0          500 

预期结果:

   credit  debit        total 
0    1000      0         1000 
1       0    100          900 
2       0    200          700 
3     500      0         1200