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

Convert Exchange Rate API JSON TO Pandas Data Frame

Im hitting a free exchange rate API to get currency exchange rates which I want to convert into a pandas data frame and store.

Nice simple code to get it

import requests

url = 'https://api.exchangerate.host/latest?base=USD'
response = requests.get(url)
data = response.json()

print(data)

The response comes out like

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

{ 
'success': True, 
'base': 'EUR', 
'date': '2023-02-17', 
'rates': 
{'AED': 3.907946, 'AFN': 94.663995, 'ALL': 115.358789...........etc}
}

I want to convert this to a pandas data frame that looks like


   date    | base | currency | rate
------------------------------------------
2023-02-17 | EUR  |   AED    | 3.907946
2023-02-17 | EUR  |   AFN    | 94.663995
2023-02-17 | EUR  |   ALL    | 115.358789

Just can figure out how to get the columns and rows like I want.

Cheers for your help.

>Solution :

# Load the currecy, rate pairs into two colums
rates_df = pd.DataFrame(data['rates'].items(), columns=['currency','rate'])

# Add the constant date and base columns
rates_df['date'] = data['date']
rates_df['base'] = data['base']

# re-order the colmns
rates_df = rates_df[['date', 'base', 'currency', 'rate']]

rates_df
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