pandas 将Dataframe转换为Nested Json [英] Pandas convert Dataframe to Nested Json

查看:184
本文介绍了 pandas 将Dataframe转换为Nested Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题本质上与此相反:



从深层嵌套的JSON创建一个Pandas DataFrame



我想知道是否可以做相反的。给出一张表:

 图书馆级学校2013年大学总计
200 MS_AVERY UGRAD一般学习GEST 5079
201 MS_AVERY UGRAD一般研究HIST 5
202 MS_AVERY UGRAD一般研究MELC 2
203 MS_AVERY UGRAD一般研究PHIL 10
204 MS_AVERY UGRAD一般研究物品1
205 MSAVERY UGRAD一般研究POLS 53

是否可以生成一个嵌套的dict(或JSON),如:



dict:

  {'MS_AVERY':
{'UGRAD':
{'GENERAL STUDIES':{'GEST':5}
{'MELC':2}

...
/ pre>

解决方案

似乎并不难创建一个函数将构建递归字典给您的 DataFrame object:

  def fdrec(df) :
drec = dict()
ncols = df.values.shape [1]
在df.values中的行:
d = drec
for j,col in枚举(行[: - 1]):
如果不是在d.keys()中的col:
如果j!= ncols-2:
d [col] = {}
d = d [col]
else:
d [col] = line [-1]
else:
如果j!= ncols-2:
d = d [col ]
return drec

这将产生:

  {'MS_AVERY':
{'UGRAD':
{'GENERAL STUDIES':{'PHYS':1L,
' POLS':53L,
'PHIL':10L,
'HIST':5L,
'MELC':2L,
'GEST':5079L}}}}


My question is essentially the opposite of this one:

Create a Pandas DataFrame from deeply nested JSON

I'm wondering if it's possible to do the reverse. Given a table like:

     Library  Level           School Major  2013 Total
200  MS_AVERY  UGRAD  GENERAL STUDIES  GEST        5079
201  MS_AVERY  UGRAD  GENERAL STUDIES  HIST           5
202  MS_AVERY  UGRAD  GENERAL STUDIES  MELC           2
203  MS_AVERY  UGRAD  GENERAL STUDIES  PHIL          10
204  MS_AVERY  UGRAD  GENERAL STUDIES  PHYS           1
205  MS_AVERY  UGRAD  GENERAL STUDIES  POLS          53

Is it possible to generate a nested dict (or JSON) like:

dict:

{'MS_AVERY': 
    { 'UGRAD' :
        {'GENERAL STUDIES' : {'GEST' : 5}
                             {'MELC' : 2}

 ...

解决方案

It seems not hard to create a function will build the recursive dictionary given your DataFrame object:

def fdrec(df):
    drec = dict()
    ncols = df.values.shape[1]
    for line in df.values:
        d = drec
        for j, col in enumerate(line[:-1]):
            if not col in d.keys():
                if j != ncols-2:
                    d[col] = {}
                    d = d[col]
                else:
                    d[col] = line[-1]
            else:
                if j!= ncols-2:
                    d = d[col]
    return drec

which will produce:

{'MS_AVERY':
    {'UGRAD':
        {'GENERAL STUDIES': {'PHYS': 1L, 
                             'POLS': 53L,
                             'PHIL': 10L,
                             'HIST': 5L,
                             'MELC': 2L,
                             'GEST': 5079L}}}}

这篇关于 pandas 将Dataframe转换为Nested Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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