2

I have dictionary as shown below

d1:

{'teachers': 49, 
      'students': 289,  
      'R': 3.7, 
      'holidays': 165, 
      'Em': {'from': '2020-02-29T20:00:00.000Z', 'to': '2020-03-20T20:00:00.000Z', 
                  'F': 3, 'C': 2},
      'OS':18 
      'sC': {'from': '2020-03-31T20:00:00.000Z', 'to': '2020-05-29T20:00:00.000Z', 
                  'F': 25, 'C': 31}}

I would like to convert above dictionary as a dataframe as shown below in pandas.

teachers  students R   holidays  Em_from     Em_to       Exam_F  Exam_C  OS  sC_from         sC_to     sC_F   sC_C
49        289      3.7 165       2020-02-29  2020-03-20  3       2       18  2020-03-31  2020-05-29    25     31
Danish
  • 2,719
  • 17
  • 32

1 Answers1

3

You're probably looking for pandas.json_normalize:

d = {'teachers': 49,
      'students': 289,
      'R': 3.7,
      'holidays': 165,
      'Em': {'from': '2020-02-29T20:00:00.000Z', 'to': '2020-03-20T20:00:00.000Z',
                  'F': 3, 'C': 2},
      'OS':18,
      'sC': {'from': '2020-03-31T20:00:00.000Z', 'to': '2020-05-29T20:00:00.000Z',
                  'F': 25, 'C': 31}}


print(pd.json_normalize(d, sep='_'))

Prints:

   teachers  students    R  ...                     sC_to  sC_F sC_C
0        49       289  3.7  ...  2020-05-29T20:00:00.000Z    25   31

[1 rows x 13 columns]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Added similar question, pls look into this, if you have some time https://stackoverflow.com/questions/63364989/convert-a-dictionary-of-dictionary-into-a-row-wise-dataframe-in-pandas – Danish Aug 11 '20 at 19:21