Home > Mobile >  Add new columns to existing dataframe with loops and conditions
Add new columns to existing dataframe with loops and conditions

Time:11-26

I have two dataframes. One is excel file and another will be created by user inputs. Based on the user inputs and conditions on columns in the 1st dataframe, new columns should be added to 1st dataframe with calculations. I have wrote the code, which was successful for the test data, but the results are not coming to dataframe. Any help?

1st Dataframe: Data columns (total 9 columns):

Column Non-Null Count Dtype


0 DDO Code 8621 non-null object
1 ULB Name 8621 non-null object
2 Dist. 8621 non-null object
3 Div. 8621 non-null object
4 Kgid No 8621 non-null int64
5 Name Of The Official 8621 non-null object
6 PRAN Number 8621 non-null float64
7 Join Date 8621 non-null datetime64[ns] 8 Present Basic 8621 non-null int64
dtypes: datetime64ns, float64(1), int64(2), object(5)

2nd Dataframe will be created by user inputs: enter image description here

from the above data, I need to append 'n' columns based on the user inputs with loops and condition.

here is the code:

for a,b in zip(month_data.month_list, month_data.month_range):
    for i,x in zip(contr_calc_new["Join Date"],contr_calc_new['Present Basic']):
        if i.date().strftime('%Y-%m') == b.date().strftime('%Y-%m'):
            contr_calc_new[a] = 0
        else:
            contr_calc_new[a] = int(((x   (x*rate)//100)*14//100))

this code is working for test data, but the results are not appending to the 1st dataframe by the calculation based on 2nd dataframe.

i need the result should be like below: if [join date] column is equal to year & month entered by user, it must return zero, else it should return some calculation. Advance thanks for the help.

CodePudding user response:

Finally I found the proper code. Thank you for your replies.

for a,b in zip(month_data.month_list, month_data.month_range):
    contr_calc_new[a] = np.where(contr_calc_new['Join Date'].dt.strftime('%Y-%m') == b.date().strftime('%Y-%m'),0,((contr_calc_new['Present Basic']   (contr_calc_new['Present Basic']*da_rate)//100)*14//100).astype(int))

CodePudding user response:

you can use the pandas.DataFrame fuction "join()" whichcan be used like this:

df1 = df1.join(df2)
  • Related