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

Python: replace columns using dictionary

I have a DataFrame that looks like this:

df:
date        price region        currency
2022-01-01  1     NorthAmerica  UnitedStatesDollar
2022-01-01  1.28  NorthAmerica  CanadianDollar
2022-01-01  1.42  Oceania       AustralianDollar
2022-01-02  1     NorthAmerica  UnitedStatesDollar
2022-01-02  1.29  NorthAmerica  CanadianDollar
2022-01-02  1.41  Oceania       AustralianDollar

I have a dictionary as follows:

currency_dict = [
  {
    'symbol': 'USD',
    'region': 'NorthAmerica',
    'currency': 'UnitedStatesDollar',
  },
  {
    'symbol': 'CAD',
    'region': 'NorthAmerica',
    'currency': 'CanadianDollar',
  },
  {
    'symbol': 'AUD',
    'region': 'Oceania',
    'currency': 'AustralianDollar',
  },
];

I want to use the dictionary to get the following DataFrame:

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

df:
date        price  symbol
2022-01-01  1      USD
2022-01-01  1.28   CAD
2022-01-01  1.42   AUD
2022-01-02  1      USD
2022-01-02  1.29   CAD
2022-01-02  1.41   AUD

I have tried df.replace(currency_dict, inplace=True) but I am not sure how that would work with replacing two columns.

Thank you in advance.

EDIT: This is a list of dictionaries! Thanks for all the comments

>Solution :

Another example:

df_currency = pd.DataFrame(currency_dict) # currency_dict actually a list of dict!!
result = pd.merge(df, df_currency)[['date', 'price', 'symbol']]

References:

https://realpython.com/pandas-merge-join-and-concat/

https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging

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