首页 > 解决方案 > 列表的嵌套字典到数据框

问题描述

我有一本这样的字典:

 {'a': {'col_1': [1, 2], 'col_2': ['a', 'b']},
 'b': {'col_1': [3, 4], 'col_2': ['c', 'd']}}

当我尝试将其转换为数据框时,得到:

     col_1  col_2
a   [1, 2]  [a, b]
b   [3, 4]  [c, d]

但我需要的是这个:

     col_1  col_2
a      1      a
       2      b
b      3      c
       4      d

我怎样才能得到这种格式。也许我也应该改变我的输入格式?谢谢你的帮助=)

标签: pythonpandasdictionary

解决方案


您可以使用pd.DataFrame.from_dict设置orient='index',以便将字典键设置为数据框的索引,然后通过应用展开所有列pd.Series.explode

pd.DataFrame.from_dict(d, orient='index').apply(pd.Series.explode)

  col_1 col_2
a     1     a
a     2     b
b     3     c
b     4     d

推荐阅读