mercredi 12 mai 2021

IF-ELSE condition in a function

I need to read in bunch of i/p dataframes based on some conditions and then merge them and finally create dataframes as 'merge_m0', 'merge_m1', 'merge_m2' and so on.

In the actual code, I need to read about 20 dataframes. But, for simplicity and ease of understanding, I'm showing for 3 dataframes and below is the code which is working fine up to 'merge'.

However, for the IF-ELSE condition after the 'merge', it's throwing syntax and all kinds of errors as I'm using globals() to create merge_m0,merge_m1,merge_m2....dataframes and not sure how to go about with it.

INPUT dataframes

df0=pd.DataFrame({'id':[1,2,4],'m0_val':[1,8,10],'name':['A','B','C'],'m0_orig_val':[2,3,4],'m0_int_dt':['07/15/2019','03/21/2019','08/10/2019'],'m0_bpo_dt':['10/15/2019','04/12/2019','06/08/2019']})
df1=pd.DataFrame({'id':[1,2,4],'m1_val':[8,10,1],'name':['D','E','F'],'m1_orig_val':[2,3,4],'m1_int_dt':['02/11/2018','04/06/2019','11/22/2019'],'m1_bpo_dt':['02/15/2018','09/11/2019','12/14/2019']})
df2=pd.DataFrame({'id':[1,2,4],'m2_val':[1,10,8],'name':['G','H','I'],'m2_orig_val':[2,3,4],'m2_int_dt':['10/01/2019','09/03/2018','12/22/2017'],'m2_bpo_dt':['11/15/2018','01/12/2019','08/08/2019']})

Code

import pandas as pd
import datetime

mydate1=datetime.date(2019,12,31)

df_list=[]
for i in range(0,3):
    df_list.append(globals()[f'df{i}']) #appending all the above i/p dataframes to a list

def comb_mths(i):
    dfa = df_list[i]
    dfb = df_list[i+1]
    dfma = dfa[dfa.iloc[:, 1].isin([1,8])] 
    dfmb = dfb[(dfb.iloc[:, 1].isin([8,10])) & (dfb.iloc[:, 3].isin([2,3,4]))]
    globals()[f"merge_m{i}"]  = dfma.merge(dfmb, how='inner', on=['id'])

    if globals()[f"merge_m{i}"][globals()[f"m{i+1}_orig_val"].isin(2,4):
        globals()[f"merge_m{i}"][f'diff'] = mydate1-globals()[f'merge_m{i}'][globals()[f'merge_m{i}'].[f'm{i+1}_int_dt']//np.timedelta64(1,'M')]
        globals()[f'merge_m{i}']['mnths'] = globals()[f"merge_m{i}"][f'diff']  - (i-1)

    elif globals()[f"merge_m{i}"][globals()[f"m{i+1}_orig_val"].isin(3,5):
        globals()[f"merge_m{i}"][f'diff'] = mydate1-globals()[f'merge_m{i}'][globals()[f'merge_m{i}'].[f'm{i+1}_bpo_dt']//np.timedelta64(1,'M')]
        globals()[f'merge_m{i}']['mnths']= globals()[f"merge_m{i}"][f'diff']  - (i-1)
        
    return globals()[f"merge_m{i}"] 

for i in range(0,2): 
    comb_mths(i)

print(merge_m0)    
print(merge_m1)

Required IF-ELSE Logic

In the above function after creating "merge_m{i}" dataframe, I need to check an if-else condition and calculate a variable called 'mnths'. Logic of the if-else condition's pseudo code is below:

Ex: when i=0 (1st iteration)
if m1_orig_val isin (2,4):
    diff = (mydate1 - m1_int_dt)//(np.timedelta64(1,'M'))
    mnths = diff - (i-1)
elif m1_orig_val isin (3,5):
    diff = (mydate1 - m1_bpo_dt)//(np.timedelta64(1,'M'))
    mnths = diff - (i-1)

Ex: when i=1 (2nd iteration)

if m2_orig_val isin (2,4):
    diff = (mydate1 - m2_int_dt)//(np.timedelta64(1,'M'))
    mnths = diff - (i-1)
elif m2_orig_val isin (3,5):
    diff = (mydate1 - m2_bpo_dt)//(np.timedelta64(1,'M'))
    mnths = diff - (i-1)

Appreciate if anyone can please show me how do I add this if-else condition in the above function as I'm not sure how to do this using globals() and it's throwing syntax and other errors? OR Pls let me know if there is any easy/better alternative to get this done. Thanks!!

Aucun commentaire:

Enregistrer un commentaire