给出2个数据集:df,df1
df = account numbers with balances
Account Number Balance New Balance
1 2356.0 1945.5
3 452.5 447.5
5 120.0 61.0
9 4582.0 4580.0
20 12.0 12.0
18 235.0 294.0
14 9.5 134.5
7 124.0 -31.5
12 230.0 230.0
16 423.0 871.0
df1 = transaction details of the account numbers
Time Outgoing Account Ingoing Account Amount
915 1 9 23.0
1025 18 12 242.5
1041 7 14 120.0
1104 16 3 1227.0
1248 20 7 45.0
1250 5 18 59.0
1305 3 14 5.0
1310 3 20 4534.0
1315 3 9 15.0
1415 7 1 35.5
1426 9 16 25.0
1520 16 12 25.0
1546 18 20 118.0
1602 14 5 2136.0
1645 1 16 423.0
目标: 步骤1:在df数据框的新余额列中找到余额为负数最多的帐户。如果不存在,则算法停止。否则,请执行步骤2。 第2步:从该帐户中删除最新的支出交易(根据其时间戳记),直到其余额变为负数为止。 步骤3:更新所有帐户的余额。转到步骤1。
这是我尝试过的代码,我面临将时间戳记包含在算法中的困难,并且无法将接受的交易打印为另一张表
import pandas as pd
df['Account Number_1']=df['Account Number']
df1 = df1.sort_values(by=['Outgoing Account', 'Time'], ascending=True)
df.set_index('Account Number_1', inplace=True)
df['New Balance'] = df.Balance
for _, row in df.iterrows():
for _, row1 in df1.iterrows():
outAcnt = int(row1['Outgoing Account'])
inAcnt = int(row1['Ingoing Account'])
amt = row1.Amount
if (int(row1['Outgoing Account']) == int(row['Account Number'])):
if (int(row['Balance']) - int(row1['Amount']) > 0):
df.at[outAcnt, 'New Balance'] -= amt
df.at[inAcnt, 'New Balance'] += amt
else:
break
#data1.reset_index(inplace=True) #(X)
#data1 = data1.sort_values('Account Number') #(X)
print(df)
print(df1)
以下是预期的输出:
Account Number 01 03 05 07 09 12 14 16
Balance (£) 1910 447.5 61 4 4580 472.5 134.5 871
Accepted Transactions:
Time 0915 1025 1041 1250 1305 1426 1645
Outgoing Account 01 18 07 05 03 09 01
Ingoing Account 09 12 14 18 14 16 16
Amount 23 242.5 120 59 5 25 423