将字典的字典转换为以 pandas 为单位的行数据框 [英] Convert a dictionary of dictionary into a row wise dataframe in pandas

查看:112
本文介绍了将字典的字典转换为以 pandas 为单位的行数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的字典

d1:

{'teachers': 49, 
      'students': 289,  
      'R': 3.7, 
      'holidays': 165, 
      'E': {'from': '2020-02-29T20:00:00.000Z', 'to': '2020-03-20T20:00:00.000Z', 
                  'F': 3, 'C': 2},
      'OS':18 
      'sC': {'from': '2020-03-31T20:00:00.000Z', 'to': '2020-05-29T20:00:00.000Z', 
                  'F': 25, 'C': 31}}

我想将上述字典转换为数据框,如下所示。 / p>

I would like to convert above dictionary as a dataframe as shown below in pandas.

Params     Value
teachers   49
students   289
R          3.7
holidays   165
E_from     2020-02-29
E_to       2020-03-20
E_F        3
E_C        2
OS         18
sC_from    2020-03-31
sC_to      2020-05-29
sC_F       25
sC_C       31  

df应该有两列,标题为 params '和'值'

The df should have two columns with heading 'params' and 'value'

解决方案

您可以使用 json_normalize 然后转置数据帧:

You can use json_normalize and then tranpose the dataframe:

d = {'teachers': 49,
      'students': 289,
      'R': 3.7,
      'holidays': 165,
      'Em': {'from': '2020-02-29T20:00:00.000Z', 'to': '2020-03-20T20:00:00.000Z',
                  'F': 3, 'C': 2},
      'OS':18,
      'sC': {'from': '2020-03-31T20:00:00.000Z', 'to': '2020-05-29T20:00:00.000Z',
                  'F': 25, 'C': 31}}


df=pd.json_normalize(d, sep='_').T.reset_index().rename(columns={'index':'Params',0:'Value'})

输出:

df
Params                       Value
teachers                        49
students                       289
R                              3.7
holidays                       165
OS                              18
Em_from   2020-02-29T20:00:00.000Z
Em_to     2020-03-20T20:00:00.000Z
Em_F                             3
Em_C                             2
sC_from   2020-03-31T20:00:00.000Z
sC_to     2020-05-29T20:00:00.000Z
sC_F                            25
sC_C                            31

这篇关于将字典的字典转换为以 pandas 为单位的行数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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