Home > OS >  Python Dict pivot keys to columns and values as rows in a dataframe
Python Dict pivot keys to columns and values as rows in a dataframe

Time:12-14

Evening,

I'm new to python and using an open source api to get the longitude and latitudes for postcodes.

I have got this far but struggling on how to pivot the dictionary.

code:

import requests
import pandas as pd

url = 'https://api.getthedata.com/postcode/ST87HL'
req = requests.get(url)
data = req.json()
entries = data['data']

#print(entries)

df = pd.DataFrame.from_dict(entries, orient='index')

print(df)

which produces this result:

enter image description here

but the outcome I'm looking to achieve is the dictionary keys to be columns and the values to be rows in the dataframe

Thanks for all help.

CodePudding user response:

Quick solution will be transpose the dataframe:

df = df.T

OR:

You can create a Dataframe by putting the dictionary to a list:

import requests
import pandas as pd

url = "https://api.getthedata.com/postcode/ST87HL"
req = requests.get(url)
data = req.json()
entries = data["data"]

df = pd.DataFrame([entries])
print(df)

Prints:

  postcode status usertype  easting  northing  positional_quality_indicator  country   latitude  longitude postcode_no_space postcode_fixed_width_seven postcode_fixed_width_eight postcode_area postcode_district postcode_sector outcode incode
0  ST8 7HL   live    small   388982    357799                             1  England  53.117254  -2.166072            ST87HL                    ST8 7HL                   ST8  7HL            ST               ST8           ST8 7     ST8    7HL
  • Related