对数据帧使用apply函数

2024-09-21 00:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着模仿熊猫的月供贷款。你知道吗

信贷栏包含我从银行借的钱的数额。你知道吗

借方列包含我支付给银行的金额。你知道吗

总计列应包含剩余支付给银行的金额。基本上它包含贷方和借方列之间的减法结果)。你知道吗

我能够编写以下代码:

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

Tags: 代码importdf银行金额totalpd总计
2条回答

您可以使用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

你不需要在这里申请。你知道吗

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()传递到减法kill中,保持运行总数以获得所需的结果。你知道吗

相关问题 更多 >

    热门问题