How I can remove this nested for loops, it take too much time

Viewed 68
for i,row_1 in df_1.iterrows():
   for j, row_2 in df_2.iterrows():
      if row_1['RECKEY'] == row_2['RECKEY']:
         df_1.loc[i ,'RECKEY'] = df_2.loc[j ,'RECKEY_NEW']

How do I build a filter which does this?

I tried the following without any success.

df_1.loc[df_1.RECKEY.isin(df_2.RECKEY), 'RECKEY'] = df_2.loc['RECKEY_NEW']

Output:

Index: [])
'RECKEY_NEW'
2 Answers

Produce basic structure of your dataframe it helps in solving the problem better. this !works!

df_1.loc[df_1["RECKEY"]==df_2["RECKEY"],'RECKEY']=df_2["RECKEY"]

You should use merge, that will solve your problem.

new_df = df_1.merge(df_2[['RECKEY_NEW','RECKEY']], left_on='RECKEY', 
right_on='RECKEY')
new_df['RECKEY'] = new_df['RECKEY_NEW'].astype(int)
Related