简体   繁体   English

来自dicts的dicts列表的DataFrame

[英]DataFrame from list of dicts of dicts

I have a list of dicts where each key in the dict contains another dict : 我有一个dicts list ,其中dict中的每个键包含另一个dict

In [256]: data_list
Out[256]: 
[{'1111': {'index': 602, 'prop_1': 0, 'prop_2': 1},
  '2222': {'index': 602, 'prop_1': 0, 'prop_2': 1}},
 {'1111': {'index': 603, 'prop_1': 0, 'prop_2': 0},
  '2222': {'index': 603, 'prop_1': 1, 'prop_2': 1}}]

In [257]: index = {i.pop('index') for x in data_list for i in x.values()}

In [258]: df = DataFrame(data_list, index=index)

In [259]: df
Out[259]: 
                             1111                          2222
602  {u'prop_1': 0, u'prop_2': 1}  {u'prop_1': 0, u'prop_2': 1}
603  {u'prop_1': 0, u'prop_2': 0}  {u'prop_1': 1, u'prop_2': 1}

How can I create the following or similar pandas.DataFrame ? 如何创建以下或类似的pandas.DataFrame

index1 index2    prop_1    prop_2
602    1111      0         1
       2222      0         1
603    1111      0         0
       2222      1         1 

Considering you can transform a series of dictionaries into a multiple columns data frame by doing .apply(pd.Series) , you can stack() your original data frame to a multiIndex Series and then use .apply(pd.Series) : 考虑到您可以通过执行.apply(pd.Series)将一系列字典转换为多列数据框,您可以将原始数据框stack()到multiIndex系列,然后使用.apply(pd.Series)

df.stack().apply(pd.Series)

#            prop_1  prop_2
# 602   1111      0       1
#       2222      0       1
# 603   1111      0       0
#       2222      1       1

Solution with concat , transpose by T and set_index : 使用concat解决方案,通过Tset_index转置:

df = pd.concat([pd.DataFrame(key) for key in data_list], axis=1)
       .T
       .set_index('index', append=True)

df.index = df.index.swaplevel(0,1)
df.index.names = ['index1','index2']
print (df)
               prop_1  prop_2
index1 index2                
602    1111         0       1
       2222         0       1
603    1111         0       0
       2222         1       1

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

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