pandas long-form表嵌套json

pro*_*der 0 python json pandas

我经历过的to_jsonjson.dumps文档,并试图各种指标和类型的字典的,而且我迷路......我可以创建类似字典的名称-值对,但不是嵌套的JSON我需要的那种类型.

我开始使用这种格式的pandas数据帧:

  level_1 level_2 level_3  numeric
0   alpha     one       a        1
1   alpha     one       b        2
2   alpha     two       a        3
3   alpha     two       b        4
4    beta     one       a        5
5    beta     one       b        6
6    beta     two       a        7
7    beta     two       b        8
Run Code Online (Sandbox Code Playgroud)

我需要一个具有以下格式的JSON文件:

{"alpha": {"one": {"a": 1, "b": 1}, "two": {"a": 3, "b": 4 etc...
Run Code Online (Sandbox Code Playgroud)

Gui*_*not 6

这是一个处理所提供数据的简单最小示例.

它可以通过仅使用Pandas数据帧以及动态处理列数来增强.

import pandas as pd
import json

# Declare the nested dictionary that will hold the result
class NestedDict(dict):
    def __missing__(self, key):
        self[key] = NestedDict()
        return self[key]

# Creation of the dataframe
df = pd.DataFrame({\
'level_1':['alpha' ,'alpha' ,'alpha' ,'alpha' ,'beta' ,'beta' ,'beta' ,'beta'],\
'level_2':['one' ,'one' ,'two' ,'two' ,'one' ,'one' ,'two' ,'two'],\
'level_3':['a' ,'b' ,'a' ,'b' ,'a' ,'b' ,'a' ,'b'],\
'numeric':[1 ,2 ,3 ,4 ,5 ,6 ,7 ,8]})

# Creation of a multi-index
rr  = df.set_index(['level_1', 'level_2', 'level_3'])

d = NestedDict()
# Loop to store all elements of the dataframe in 
# the instance of NestedDict
for k in rr.iterrows():
    d[k[0][0]][k[0][1]][k[0][2]] = k[1].values[0]
# JSON output
json.dumps(d,default=str)
Run Code Online (Sandbox Code Playgroud)