Assuming I have a dataframe called df which looks like the one shown below:
Id Place
1 NY
2 Berlin
3 Paris
4 Paris
5 Berlin
And a dictionary, which has IDs as keys and places as values as shown below:
id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"}
I want to iterate through every row of the dataframe and see if the ID is contained in the id_to_place dictionary. If so, then I wanna replace the column Place of that row with the dictionary value. For instance after runninh the code I want the output to be:
Id Place
1 Berlin
2 Berlin
3 NY
4 Paris
5 Berlin
So far I have tried this code:
id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"}
for index,row in df.iterrows():
id = row['id']
place = row['place']
for item in id_to_place:
if item == str(id):
df.loc[df.id =id,'place'] = id_to_place[item]
print(df)
But when I run the code the dataframe stays unchangable. Does anyone have an idea as to why this happens? I appreciate any help!
Use Series.map
for replace matched values, then replace NaN
s by original column by Series.fillna
:
df['Place'] = df['Id'].map(id_to_place).fillna(df['Place'])
print (df)
Id Place
0 1 Berlin
1 2 Berlin
2 3 NY
3 4 Paris
4 5 Berlin
Your current method isn't working because your items in your dictionaries are integers and you're checking them against str(id) which always returns False. If you remove the str and just check item against id then it works.
id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"}
for index,row in df.iterrows():
id = row['id']
place = row['place']
for item in id_to_place:
if item == id: # this line changed
df.loc[df.id =id,'place'] = id_to_place[item]
print(df)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With