Converting an ordered dictionary into a dataframe - Data handling - AliceBlue

Viewed 62

Newbie alert, please bear

the data i have right now after running the line of code below is

Input-

data = pd.DataFrame(alice._AliceBlue__master_contracts_by_symbol)

Output-

    Index                                       NSE
1018GS2026 GS   Instrument(exchange='NSE', token=6833, symbol='1018GS2026 GS', name='GOI LOAN 10.18% 
                2026', expiry=None, lot_size='1')
1025GS2021 GS   Instrument(exchange='NSE', token=6819, symbol='1025GS2021 GS', name='GOI LOAN 10.25% 
                2021', expiry=None, lot_size='1')
116GS2020 GS    Instrument(exchange='NSE', token=6814, symbol='116GS2020 GS', name='GOI LOAN 11.60% 
                2020', expiry=None, lot_size='1')
182D010721 TB   Instrument(exchange='NSE', token=1776, symbol='182D010721 TB', name='GOI TBILL 182D- 
                01/07/21', expiry=None, lot_size='100')
182D020921 TB   Instrument(exchange='NSE', token=2593, symbol='182D020921 TB', name='GOI TBILL 182D- 
                02/09/21', expiry=None, lot_size='100')

I want a dataframe like this from inside the above dataframe

    Index      Exchange  token     symbol             name            expiry  lot_size 
1018GS2026 GS    NSE     6833   1018GS2026 GS  GOI LOAN 10.18% 2026    None      1
1025GS2021 GS    NSE     6819   1025GS2021 GS  GOI LOAN 10.25% 2021    None      1
116GS2020 GS     NSE     6814   116GS2020 GS   GOI LOAN 11.60% 2020    None      1
182D010721 TB    NSE     1776   182D010721 TB  GOI TBILL 182D-01/07/21 None     100
182D020921 TB    NSE     2593   182D020921 TB  GOI TBILL 182D-02/09/21 None     100

Any suggestions guys?, what should i do? Note - alice._AliceBlue__master_contracts_by_symbol is an ordered dictionary

1 Answers

You can try json_normalize:

df = pd.json_normalize(df['NSE'])

If necessary convert named tuples to dictionaries by _asdict first:

df = pd.json_normalize(df['NSE'].apply(lambda x: x._asdict()))

Or:

df = pd.json_normalize([x._asdict() for x in df['NSE']]).set_index(df.index)
Related