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
but I need to have this data available in opposite way as below:
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()))