将字典的嵌套列表转换为pandas DataFrame

时间:2018-12-29 17:08:58

标签: python python-3.x pandas list dictionary

有人可以建议我将字典列表转换为pandas数据框的有效方法吗?

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'}]]

提供的示例输入中的字典键是相同的,预期的输出是

Output =      name       roll_no       gender
          0   tom        1234          male
          1   sam        1212          male
          2   kavi       1235          female
          3   maha       1211          female

1 个答案:

答案 0 :(得分:2)

您将需要使用itertools.chain使输入变平,然后可以调用pd.DataFrame构造函数。

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