nisahc
nisahc

Reputation: 23

How to convert nested dictionary to dataframe in Python

I have a list contain nested dictionary, I want to convert them to pandas dataframe.

My input data is below

my_list = [{'ticker': 'CompanyA',
  'Cash Cycle': ['3M/2018', '3M/2017', '2017', '2016'],
  'A/R Turnover (Times)': ['1', '2', '3', '4']},
 {'ticker': 'CompanyB',
  'Cash Cycle': ['3M/2018', '3M/2017', '2017', '2016'],
  'A/R Turnover (Times)': ['5', '6', '7', '8']}]

I tried to convert with pd.Dataframe(my_list) and result is below

https://i.sstatic.net/kr7zJ.png

Please tell me how to get result below ?

enter image description here

Upvotes: 0

Views: 61

Answers (1)

Sunitha
Sunitha

Reputation: 12015

import pandas as pd
df_list = [pd.DataFrame(d) for d in my_list]

df = pd.concat(df_list).reset_index(drop=False)
df
   index    ticker Cash Cycle A/R Turnover (Times)
0      0  CompanyA    3M/2018                 7.57
1      1  CompanyA    3M/2017                 7.60
2      2  CompanyA       2017                 8.69
3      3  CompanyA       2016                 8.25
4      0  CompanyB    3M/2018                 7.57
5      1  CompanyB    3M/2017                 7.60
6      2  CompanyB       2017                 8.69
7      3  CompanyB       2016                 8.25


   ticker     Cash Cycle    A/R Turnover (Times)
0  CompanyA    3M/2018      7.57
1  CompanyA    3M/2017      7.60
2  CompanyA       2017      8.69
3  CompanyA       2016      8.25
0  CompanyB    3M/2018      7.57
1  CompanyB    3M/2017      7.60
2  CompanyB       2017      8.69
3  CompanyB       2016      8.25

Upvotes: 2

Related Questions