Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nested list of dictionaries to pandas DataFrame

Can anyone suggest me an efficient way to convert list of list of dictionaries as pandas dataframe?

Input = [[{'name':'tom','roll_no':1234,'gender':'male'},
          {'name':'sam','roll_no':1212,'gender':'male'}],
          [{'name':'kavi','roll_no':1235,'gender':'female'},
          {'name':'maha','roll_no':1211,'gender':'female'}]]

The dictionary keys are same in the sample input provided and an expected output is,

Output =      name       roll_no       gender
          0   tom        1234          male
          1   sam        1212          male
          2   kavi       1235          female
          3   maha       1211          female
like image 478
Mahamutha M Avatar asked Oct 26 '25 08:10

Mahamutha M


1 Answers

You will need to flatten your input using itertools.chain, and you can then call the pd.DataFrame constructor.

from itertools import chain
pd.DataFrame(list(chain.from_iterable(data)))

   gender  name  roll_no
0    male   tom     1234
1    male   sam     1212
2  female  kavi     1235
3  female  maha     1211
like image 187
cs95 Avatar answered Oct 27 '25 21:10

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!