在迭代过程中不更新数据帧(itertuples),但在函数之外独立工作

2024-05-16 13:13:46 发布

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

前面我为每个余额读数创建了一个数据帧,其中在特定的一天包含一个0。但是当运行while循环时,if语句永远找不到非零平衡读数,即使它确实存在。你知道吗

我独立地运行了一个特定帐户的代码,它遍历了我的所有代码,找到了以前的余额并替换了它,但我必须按顺序执行,而不是全部在一个函数中。我猜是这个问题的根源。你知道吗

# df looks like this with amount_y being the balance (ignore amount_x for now, it represents transaction amount/day/account):

# accrual_date | financial_account_id | amount_x | amount_y

def updateBalance(df):
    index = 0
    for row in df.itertuples():
        old_balance = 0
        index_when_condition_met = 0

        if df.loc[index,'amount_y'] == 0:
            financial_account_id_search = df.loc[index,'financial_account_id']
            accrual_date_search = df.loc[index,'accrual_date']
            ordered = df[df['financial_account_id'].str.match(financial_account_id_search)].sort_values(by='accrual_date').reset_index(drop=True)

            for row2 in ordered.itertuples():

                index_when_condition_met = ordered[(ordered['accrual_date'].str.match(accrual_date_search)) & (ordered['amount_y'] == 0)].index.values[0] #takes first balance reading if more than one balance reading of 0 took place on same day


                while index_when_condition_met > 0:

                    if ordered.loc[index_when_condition_met - 1,'amount_y'] != 0: # previous balance is not 0,

                        old_balance = ordered.loc[index_when_condition_met - 1,'amount_y']
                        break
                    else: # previous balance is 0, need to check earlier entries
                        index_when_condition_met = index_when_condition_met - 1

                if index_when_condition_met == 0:
                    old_balance = 0
                    df.at[index,"amount_y"] = old_balance # might be redundant

                else:
                    df.at[index,"amount_y"] = old_balance

        index = index + 1                                                                        
    return df
updateBalance(df)

e的新结果数据帧应该用非零的前一个余额(如果存在)替换所有0值。你知道吗


Tags: iddfdateindexifaccountconditionamount