vendredi 1 juillet 2016

How do I use a mapping variable to re-index a dataframe?

I have the following data frame:

                  population   GDP
country
United Kingdom    4.5m         10m
Spain             3m           8m
France            2m           6m

I also have the following information in a 2 column dataframe(happy for this to be made into another datastruct if that will be more beneficial as the plan is that it will be sorted in a VARS file.

county           code
Spain            es
France           fr
United Kingdom   uk

The 'mapping' datastruct will be sorted in a random order as countries will be added/removed at random times.

What is the best way to re-index the data frame to its country code from its country name?

Is there a smart solution that would also work on other columns so for example if a data frame was indexed on date but one column was df['county'] then you could change df['country'] to its country code? Finally is there a third option that would add an additional column that was either country/code which selected the right code based on a country name in another column?

Aucun commentaire:

Enregistrer un commentaire