将字典嵌套到 Pandas DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49115118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:16:32  来源:igfitidea点击:

Nested dictionary to pandas DataFrame

pythonpandasdictionarydataframe

提问by ba_ul

My data looks like this:

我的数据如下所示:

{ outer_key1 : [ {key1: some_value},
                {key2: some_value},
                {key3: some_value} ],
  outer_key2 : [ {key1: some_value},
                {key2: some_value},
                {key3: some_value} ] }

The inner arrays are always the same lengths. key1, key2, key3 are also always the same.

内部数组的长度始终相同。key1、key2、key3 也总是相同的。

I want to convert this to a pandas DataFrame, where outer_key1, outer_key2, ... are the index and key1, key2, key3 are the columns.

我想将其转换为 Pandas DataFrame,其中 outer_key1、outer_key2、... 是索引,key1、key2、key3 是列。

Edit:

编辑:

There's an issue in the data, which I believe is the reason the given solutions are not working. In a few cases, in the inner array there are three Nones instead of the three dictionaries. Like this:

数据中存在问题,我认为这是给定解决方案不起作用的原因。在少数情况下,内部数组中有三个Nones 而不是三个字典。像这样:

outer_key3: [ None, None, None ]

outer_key3: [ None, None, None ]

采纳答案by YOBEN_S

Data from Jpp

来自 Jpp 的数据

pd.Series(d).apply(lambda x  : pd.Series({ k: v for y in x for k, v in y.items() }))
Out[1166]: 
    K1  K2  K3
O1   1   2   3
O2   4   5   6

Update

更新

pd.Series(d).apply(lambda x  : pd.Series({ k: v for y in x for k, v in y.items() }))
Out[1179]: 
     K1   K2   K3
O1  1.0  2.0  3.0
O2  4.0  5.0  6.0
O3  NaN  NaN  NaN

回答by jpp

Here's one way:

这是一种方法:

d = { 'O1' : [ {'K1': 1},
               {'K2': 2},
               {'K3': 3} ],
      'O2' : [ {'K1': 4},
               {'K2': 5},
               {'K3': 6} ] }

d = {k: { k: v for d in L for k, v in d.items() } for k, L in d.items()}

df = pd.DataFrame.from_dict(d, orient='index')

#     K1  K2  K3
# O1   1   2   3
# O2   4   5   6

Alternative solution:

替代解决方案:

df = pd.DataFrame(d).T

More cumbersome method for Nonedata:

比较繁琐的None数据方法:

d = { 'O1' : [ {'K1': 1},
               {'K2': 2},
               {'K3': 3} ],
      'O2' : [ {'K1': 4},
               {'K2': 5},
               {'K3': 6} ],
      'O3' : [ {'K1': None},
               {'K2': None},
               {'K3': None} ] }

d = {k: v if isinstance(v[0], dict) else [{k: None} for k in ('K1', 'K2','K3')] for k, v in d.items()}
d = {k: { k: v for d in L for k, v in d.items() } for k, L in d.items()}

df = pd.DataFrame.from_dict(d, orient='index')

#      K1   K2   K3
# O1  1.0  2.0  3.0
# O2  4.0  5.0  6.0
# O3  NaN  NaN  NaN