python - 将相同字典的列表转换为 Dataframe

标签 python pandas dataframe

我有一个这样的列表:

[{'FirstOfficer': '1'}, {'SecondOfficer': '2'}, {'ThirdOfficer': '3'},{'FirstOfficer': '4'}, {'SecondOfficer': '5'}, {'ThirdOfficer': '6'},{'FirstOfficer': '7'}, {'SecondOfficer': '8'}, {'ThirdOfficer': '9'},{'FirstOfficer': '10'}, {'SecondOfficer': '11'}, {'ThirdOfficer': '12'}]

我想将其转换为数据帧,但我得到了这样的数据帧:

   FirstOfficer SecondOfficer ThirdOfficer
0             1           NaN          NaN
1           NaN             2          NaN
2           NaN           NaN            3
3             4           NaN          NaN
4           NaN             5          NaN
5           NaN           NaN            6
6             7           NaN          NaN
7           NaN             8          NaN
8           NaN           NaN            9
9            10           NaN          NaN
10          NaN            11          NaN
11          NaN           NaN           12

列名称可以是任何内容,因此我无法对其进行硬编码。

预期的数据帧是:

   FirstOfficer SecondOfficer ThirdOfficer
0             1           2          3
1             4           5          6
2             7           8          9
3            10          11         12

有人能给我建议一个解决方案吗?

如有任何帮助,我们将不胜感激。

最佳答案

使用defaultdict来存储要按字典键列出的值:

from collections import defaultdict

d = defaultdict(list)
for x in L:
    a, b = tuple(x.items())[0]
    d[a].append(b)
print (d)


df = pd.DataFrame(d)
print (df)
  FirstOfficer SecondOfficer ThirdOfficer
0            1             2            3
1            4             5            6
2            7             8            9
3           10            11           12

关于python - 将相同字典的列表转换为 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56127045/

相关文章:

python - 如何在python中根据月、年、时间列标题编写csv文件名

python - 基于 Pandas DataFrame 中另一列的 Sum 列

python - 在 Pandas 中进行 t-1 计算的更快方法

python - 将混合数据转换为分类数据 : dataframe

python - 在 OS X Lion 上强制 Python 为 32 位

python - 无法删除 Django 中特定条目的缓存

python - Pandas 滚动删除了复杂的虚部......缺陷或特征?

python - 查找 Pandas 中每列的每个唯一值的百分比

使用另一个数据帧作为 R 中的键替换数据帧中的所有值

python - 操作 Pandas 数据框的数据