Pandas数据框在迭代过程中(Itupuples)未更新,但在函数外部独立工作

时间:2019-06-21 02:45:06

标签: python pandas dataframe

之前,我为每个在特定日期包含0的余额读数创建一个数据框。但是,当需要运行while循环时,if语句永远不会找到非零余额读数,即使它确实存在。

我独立地为一个特定帐户运行代码,它遍历了我所有的代码,找到了之前的余额并替换了它,但是我必须顺序执行,而不是全部在一个功能中执行。我的猜测是itetuples是此问题的根源。

# 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值。

0 个答案:

没有答案