accntid transcode transamt balance
1 Credit 20 4000
1 Debit 50
1 Credit 80
2 Debit 60 5000
2 Credit 40
2 Debit 120
2 Credit 130
嗨,大家好。我有一个包含上述数据的数据框,我想根据下一行的交易代码和交易金额来更新余额。知道如何在Dataframe上来回遍历
答案 0 :(得分:0)
IIUC:
df1 = df.assign(transamt = np.where(df['transcode'] == 'Debit',-1,1) * df['transamt'])
df1['balance1'] = (df1.balance
.fillna(df1.groupby('accntid', group_keys=False)
.apply(lambda x: x.balance.fillna(df1.transamt).cumsum())))
print(df1)
输出:
accntid transcode transamt balance balance1
0 1 Credit 20 4000.0 4000.0
1 1 Debit -50 NaN 3950.0
2 1 Credit 80 NaN 4030.0
3 2 Debit -60 5000.0 5000.0
4 2 Credit 40 NaN 5040.0
5 2 Debit -120 NaN 4920.0
6 2 Credit 130 NaN 5050.0