Home > Mobile >  Replace values in pandas column with value in dictionary
Replace values in pandas column with value in dictionary

Time:08-17

I have a list of dictionaries that looks like this:

[{'idcust': '123', 'LOC_NAME_STATE': 'BRUNSWICK_WA'},
 {'idcust': '124', 'LOC_NAME_STATE': 'CANNING VALE_WA'}]

I have a df that looks like this:

    IDCUST  NAMECITY.1
0   123 RICHMOND
1   124 MACLEAY ISLAND
2   125 VICTORIA POINT

I want to replace the values in NAMECITY.1 column where the 'idcust' value matches the 'IDCUST' column in the df.

CodePudding user response:

list_of_dicts = [{'idcust': '123', 'LOC_NAME_STATE': 'BRUNSWICK_WA'},
 {'idcust': '124', 'LOC_NAME_STATE': 'CANNING VALE_WA'}]

df2 = pd.DataFrame(list_of_dicts)

df['NAMECITY.1'] = (df['IDCUST'].astype(str)
.map(df2.set_index('idcust').squeeze())
.fillna(df['NAMECITY.1']))

Output:

   IDCUST       NAMECITY.1
0     123     BRUNSWICK_WA
1     124  CANNING VALE_WA
2     125   VICTORIA POINT

CodePudding user response:

I got it to work after changing the dictionary to this:

   suburb_dict =  {'123' : 'BRUNSWICK_WA', '124' : 'CANNING VALE_WA'}

Then applying a lambda function:

cust_suburb_df['NAMECITY.1'] = cust_suburb_df['IDCUST'].apply(lambda x: suburb_dict[x] if x in suburb_dict else cust_suburb_df[cust_suburb_df['IDCUST'] == x]['NAMECITY.1'].values[0])

I wonder if there is a more pythonic way of doing it using apply() and a lambda function?

  • Related