使用对熊猫数据框的应用功能

时间:2019-02-21 16:17:01

标签: python pandas

我正在尝试模拟熊猫每月付款的贷款。

信贷列包含我从银行借的钱。

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

总计列应包含应支付给银行的金额。基本上,它包含“贷方”和“借方”列之间的减法结果。

我能够编写以下代码:

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

2 个答案:

答案 0 :(得分:6)

您可以使用cumsum

df['total'] = (df.credit - df.debit).cumsum()

print(df)

输出

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

答案 1 :(得分:2)

您不需要在这里申请。

import pandas as pd

df = pd.DataFrame({'credit': [1000, 0, 0, 500],
                   'debit': [0, 100, 200, 0]})

df['Total'] = (df['credit'] - df['debit']).cumsum()

print(df)

输出

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

apply无效的原因是因为apply在每一行执行,而不是在每次减法后保持运行总数。将cumsum()传递到减法终止中,可以使运行总计保持期望的结果。