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

pandas expand rows with alternative names (multiple and change rows)

I’m trying to format following dataframe (it can be copied to clipboard and read by pd ):

enter image description here

Given the dictionary where for each country there is a list of alternative names, I am trying to "explode" values with duplicate rows where country values are updated.
Dictonary to update country_names:

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

{
    'UAE':['United Arab Emirates', 'UAE'],
    'Rep of Tunisia': ['Tunisia','Rep of Tunisia']
}

desired result:

enter image description here

It seemed like an easy thing but I stuck, any help appreciated.

>Solution :

You can map your dictionary, then explode:

out = (df.assign(country=df['country'].map(country_names))
         .explode('country', ignore_index=True)
       )

output:

                country      period
0  United Arab Emirates  2022-01-01
1                   UAE  2022-01-01
2               Tunisia  2022-10-01
3        Rep of Tunisia  2022-10-01
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