Iterate through a dictionary and update dataframe values

Tags: , , ,



i have a dictionary and a df column contains the country code “BHR”,”SAU”,”ARE”..etc

how to update this column so if it find any of the dict keys it will create new column [“TIMEZONE”] row to the dict value. also add if statement that if the row is not equal to the key add a default value

TimeZoneTableInplace={'BHR':'(GMT+03:00) Baghdad, Kuwait, Riyadh',
                      'SAU':'(GMT+03:00) Baghdad, Kuwait, Riyadh',
                      'ARE':'(GMT+04:00) Abu Dhabi, Muscat'}
                  

here is my try but it is only updating the last key in the dictionary.

for i,x in TimeZoneTableInplace.items():
          
    df['TIMEZONE']=np.where(df['COUNTRY']==i,x,'(GMT+03:00) Baghdad, Kuwait, Riyadh'))

Answer

This is map:

df['TIMEZONE'] = (df['COUNTRY'].map(TimeZoneTableInplace)
                    .fillna('(GMT+03:00) Baghdad, Kuwait, Riyadh')
                 )


Source: stackoverflow