Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change Values in Dataframe with Values in Some Other Columns in Other Dataframe

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading