简体   繁体   English

嵌套到pandas DataFrame的字典

[英]Nested dictionary to pandas DataFrame

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 None s instead of the three dictionaries. 在某些情况下,内部数组中有三个None而不是三个字典。 Like this: 像这样:

outer_key3: [ None, None, None ]

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 None data: 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM