如何将3级字典转换为所需格式? [英] How to convert a 3-level dictionary to a desired format?

查看:88
本文介绍了如何将3级字典转换为所需格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个三级字典,像这样:

I have a 3-level dictionary like this:

data={'2016-11-28': {'area1': {'am': -0.007, 'pm': 0.008}, 'area2': {'am': 0.0, 'pm': 0.0}, 'area3': {'am': -0.01, 'pm': -0.001}},'2016-11-29':{'area1': {'am': -0.007, 'pm': 0.008}, 'area2': {'am': 0.0, 'pm': 0.0}, 'area3': {'am': -0.01, 'pm': -0.001}}}

我想将其转换为数据框,然后尝试:

I want to convert it to a dataframe, and I tried:

tickers=data['2016-11-28'].keys()
iterables=[tickers,['am','pm']]
index=pd.MultiIndex.from_product(iterables, names=['ticker', 'time'])
frame=pd.DataFrame(data,index=index)

但我知道了

                2016-11-28  2016-11-29
ticker time                        
area1  am           NaN         NaN
       pm           NaN         NaN
area3  am           NaN         NaN
       pm           NaN         NaN
area2  am           NaN         NaN
       pm           NaN         NaN

数据框中没有值,只有列名和索引名.我的代码有什么问题?有人可以帮忙吗?非常感谢!

There are no values in the dataframe, only column names and index names. What's wrong with my code? Can someone help? Thanks very much!

推荐答案

这是我自己的解决方案:三重for循环以强制字典符合{'col1':{('row1_level0', 'row1_level1'):value}}

Here is my own solution: triple for loop to force dictionary to conform to rules for hierarchical index which is {'col1':{('row1_level0', 'row1_level1'):value}}

使用时会看起来像这样

pd.DataFrame({'col1':{('rowidx0_level0', 'rowidx0_level1'):5}})

                         col1
rowidx0_level0 rowidx0_level1     5

这是实现

d = {}
for date, areas in data.items():
    d[date] = {}
    for area, times in areas.items():
        for time, value in times.items():
            d[date][(area, time)] = value 

pd.DataFrame(d)

          2016-11-28  2016-11-29
area1 am      -0.007      -0.007
      pm       0.008       0.008
area2 am       0.000       0.000
      pm       0.000       0.000
area3 am      -0.010      -0.010
      pm      -0.001      -0.001

这是实际词典d的样子:

{'2016-11-28': {('area1', 'am'): -0.007,
  ('area1', 'pm'): 0.008,
  ('area2', 'am'): 0.0,
  ('area2', 'pm'): 0.0,
  ('area3', 'am'): -0.01,
  ('area3', 'pm'): -0.001},
 '2016-11-29': {('area1', 'am'): -0.007,
  ('area1', 'pm'): 0.008,
  ('area2', 'am'): 0.0,
  ('area2', 'pm'): 0.0,
  ('area3', 'am'): -0.01,
  ('area3', 'pm'): -0.001}}

采用与@acushner链接的答案.

Adopting the answer linked to from @acushner.

dates = []
frames = []

for date, d in data.items():
    dates.append(date)
    frames.append(pd.DataFrame.from_dict(d, orient='index').stack())

pd.concat(frames, keys=dates, axis=1)

          2016-11-28  2016-11-29
area1 pm       0.008       0.008
      am      -0.007      -0.007
area2 pm       0.000       0.000
      am       0.000       0.000
area3 pm      -0.001      -0.001
      am      -0.010      -0.010

这篇关于如何将3级字典转换为所需格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆