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

标签 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

最佳答案

您需要使用 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

关于python - 将嵌套的字典列表转换为 pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53971630/

相关文章:

python numpy/scipy 查找多维数组中相对变量的计数或频率

python - 为什么 globals() 在迭代期间改变大小?

Python-bytes() 与 struct.pack()

python - 使用提供给构造函数的数据列表在数据帧构造函数中设置多索引

python - 绘制包含 HH :MM format in a single figure matplotlib 的数据帧

python - 使用 Python 搜索 Outlook 收件箱

python - 使用 Tkinter 创建烟花

python - 有效地找到二叉树中最重的路径 - python

python - 我的程序正确执行所有操作,但它以随机顺序打印输入 [Python 3,初学者]

python - 从 Pandas DataFrame 中删除列表