Home > Blockchain >  Python: convert list of dictionaries into dataframe
Python: convert list of dictionaries into dataframe

Time:01-26

[{'info':{'price':'100',
   'volume':'200000',
   'ask':'101',
   'bid':'99',
   'fee':'0',
   'spread':'2',},
  'currency':'USD',
  'ticker':'XYZ',
  'timestamp':'1643123872',
  'fee':{'cost':0, 'currency':'USD'}},
 {'info':{'price':'107',
   'volume':'220000',
   'ask':'108',
   'bid':'106',
   'fee':'0',
   'spread':'2',},
  'currency':'USD',
  'ticker':'XYZ',
  'timestamp':'1643123882',
  'fee':{'cost':0, 'currency':'USD'}}]

I want to create a dataframe with the above information with select key values. So I want to generate a dataframe that looks like this:

df:
    timestamp   currency    fee    price    ticker    volume
    1643123872  USD         0      100      XYZ       200000
    1643123882  USD         0      107      XYZ       220000

How can this be done? Notice that I have sub-keys for the 'info' key.

Thank you.

CodePudding user response:

You can use the .str accessor to extract values from dictionary columns.

Assuming data contains your input list:

df = pd.DataFrame(data)
df['price'] = df['info'].str['price']
df['volume'] = df['info'].str['volume']
df['fee'] = df['fee'].str['cost']
df[['timestamp', 'currency', 'fee', 'price', 'ticker', 'volume']]
  •  Tags:  
  • Related