Convert Exchange Rate API JSON TO Pandas Data Frame

Question:

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

{ 
'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.

Asked By: Jack Gruber

||

Answers:

# 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
Answered By: Simon Ward-Jones
import requests
import pandas as pd

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


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

print((pd.DataFrame(data)
       .reset_index()
       .rename(columns={'index': 'currency', 'rates': 'rate'})
       [['date', 'base', 'currency', 'rate']]
       .set_index('date')
       )
      )
Answered By: georgwalker45
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.