python - Pandas 将 Dataframe 转换为嵌套的 Json

标签 python json dictionary pandas

我的问题基本上与这个问题相反:

Create a Pandas DataFrame from deeply nested JSON

我想知道是否可以进行相反的操作。给定一个表格:

     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

是否可以生成嵌套的字典(或 JSON),例如:

字典:

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

 ...

最佳答案

创建一个函数似乎并不难,它将根据您的 DataFrame 对象构建递归字典:

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

这将产生:

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

关于python - Pandas 将 Dataframe 转换为嵌套的 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576869/

相关文章:

python - 基本的Python字典问题

r - 更改 R 中 ggplot geom_polygon 的颜色方案

python - 使用不同维度的子数组展平 numpy 数组

Python 服务器 "Aborted (Core dumped)"

php - Android MySql 使用 php 创建图像并将其上传到服务器

java - Spring MVC + Jackson-JsonView

python - 给定两个整数列表,在彼此距离 < O(N^2) 的范围内找到每一对

python - 为什么我使用 Translate API 的 Python App Engine 应用程序收到 ImportError : No module named apiclient. 发现错误?

javascript - Angular JS 和 Symfony2

python - 如果字段名称与 python 中的字典值匹配,则求和