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

how to convert below api reponse to dataframe in python

I have one API which returns data for a list something like below:
{‘NFO:AXISBANK23JUNFUT’: {‘instrument_token’: 9156098, ‘last_price’: 967.55}, ‘NFO:BAJAJ-AUTO23JUNFUT’: {‘instrument_token’: 9156354, ‘last_price’: 4619.15}, ‘NFO:BAJAJFINSV23JUNFUT’: {‘instrument_token’: 9179138, ‘last_price’: 1544.1}, ‘NFO:BAJFINANCE23JUNFUT’: {‘instrument_token’: 9179394, ‘last_price’: 7390.85}, ‘NFO:BALRAMCHIN23JUNFUT’: {‘instrument_token’: 9180930, ‘last_price’: 395.95}}

when I try to convert it to dataframe, primary values goes in header something like below:
image view as view is distorted in text below

              NFO:AXISBANK23JUNFUT  ...  NFO:BALRAMCHIN23JUNFUT

instrument_token 9156098.00 … 9180930.00
last_price 967.55 … 395.95

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

but I need to have this data available in opposite way as below:

enter image description here

                     instrument_token      last_price

NFO:AXISBANK23JUNFUT 9156098 967.55
NFO:BALRAMCHIN23JUNFUT 9180930 395.95

>Solution :

First your need to set the keys as index and the other nested data as columns.
You can use the following snippet Ref: Pandas from_records

samples = {'NFO:AXISBANK23JUNFUT': {'instrument_token': 9156098, 'last_price': 967.55}, 'NFO:BAJAJ-AUTO23JUNFUT': {'instrument_token': 9156354, 'last_price': 4619.15}, 'NFO:BAJAJFINSV23JUNFUT': {'instrument_token': 9179138, 'last_price': 1544.1}, 'NFO:BAJFINANCE23JUNFUT': {'instrument_token': 9179394, 'last_price': 7390.85}, 'NFO:BALRAMCHIN23JUNFUT': {'instrument_token': 9180930, 'last_price': 395.95}}
# Set the dictionary keys as index column and the nesting values as records.
df = pd.DataFrame.from_records(list(samples.values()), index=list(samples.keys()))
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