Say I have a dataframe which contains the locations of places.
df1 = pd.DataFrame({'col1': [1,2,3,4,5], 'location': ['Hackney', 'Mile End', 'Croydon', 'Edgbaston', 'Wembley'] })
Then I have a list of these places and what the main city they are contained in stored in a dictionary
dict ={
['Hackney', 'Mile End', 'Croydon', 'Wembley'] : 'London',
['Edgbaston'] : 'Birmingham'
}
Question: How could I create a new column (say df1['city']
) which uses this dictionary to populate which city each of the location
column entries is in. Note: If creating a dictionary to do this isnt the ideal way feel free to suggest an alternative.
Ideal Output: Would like something as shown below (this should generalise for more entries providing the dictionary is extended if need be).
df1 = pd.DataFrame({'col1': [1,2,3,4,5], 'location': ['Hackney', 'Mile End', 'Croydon', 'Edgbaston', 'Wembley'], 'city': ['London','London','London','Birmingham','London'] })
Tried: Using the apply method but seems to give an error
df1['city'] = df1['location'].apply(dict)