I want to change values in my datframe
student = pd.DataFrame({'id': [1,2,3,4,5,6,7,8,9,10,],
'homeground': ['TOKYO','SOUTH KOREA','RIYADH','JAPAN','TOKYO','OSAKA','SAUDI ARABIA','SEOUL','','BUSAN']})
this is the master homegroud
hg = pd.DataFrame({'id_country':[1,2,2,3,3],
'country': ['Saudi Arabia','South Korea','South Korea','Japan','Japan'],
'id_city':[11,21,22,31,32],
'city': ['RIYADH','SEOUL','BUSAN','TOKYO','OSAKA'],})
I want to change homeground values in student so the result will be like this
id homeground
1 31
2 2
3 11
4 3
5 31
6 32
7 1
8 21
9 0
10 22
>Solution :
Use:
s1 = student.homeground.map(hg.set_index('city')['id_city'])
s = hg.drop_duplicates(['country']).set_index('country')['id_country'].rename(str.lower)
s2 = student.homeground.str.lower().map(s)
student['homeground'] = s1.fillna(s2).fillna(0, downcast='int')
print (student)
id homeground
0 1 31
1 2 2
2 3 11
3 4 3
4 5 31
5 6 32
6 7 1
7 8 21
8 9 0
9 10 22