0

I have two dataframes old and new. I wanted to compare the new dataframe with old dataframe and when their is name and category match i want to append the specific value from new dataframe to old dataframe, while my code is printing the results after if condition its not appending values. Here is my code

 for old in df_old.iterrows():
    for new in df_new.iterrows():
        if (old[1]['Name'] == new[1]['Name']) & (old[1]['Category'] == new[1]['Category']):

            print(old)

            #Code below not working
            old[1]['New Category'] = new[1]['Category']
            old[1]['New Sub Category'] = new[1]['Sub-Category']
            old[1]['New Name'] = new[1]['Name']


columns

df_old = ['Name', 'JobNo', 'Category', 'Sub Category', 'New Category', 'New Sub Category', 'New Name']

df_new = ['Name',  'JobNo', 'Category', 'Sub-Category']
MikeCode
  • 91
  • 11
  • Don't update an object while you are looping through it, it's not a good practice. – Daniel Lima Jan 30 '20 at 16:36
  • What's the alternative? I am quite a new to python and pandas. Any suggestions will be appreciated – MikeCode Jan 30 '20 at 16:39
  • 1
    Iterating a dataframe is almost never the best way to do a thing; iterating two at once less so. Please provide a sample of your input and your preferred output so we can better understand your problem – G. Anderson Jan 30 '20 at 16:39
  • I have two key values to compare so I need something like `on='name' & 'category'`. Will this work with merge? – MikeCode Jan 30 '20 at 16:45
  • 1
    `df_old.merge(df_new, on=['Name' ,'Category'], how='left' )` worked like Charm – MikeCode Jan 30 '20 at 16:53

0 Answers0