2014-05-02 71 views
0

我已经通过了to_jsonjson.dumps文档,并尝试了不同种类的索引和字典,我迷路了......我可以创建类似字典的名称 - 值对,但不是我需要的嵌套json类型。熊猫长形表嵌套json

我开始用此格式的大熊猫数据帧:

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 

而且我需要以下格式的JSON文件:

{"alpha": {"one": {"a": 1, "b": 1}, "two": {"a": 3, "b": 4 etc... 

回答

4

这里是关于工作的一个简单的小例子,提供的数据。

它可以通过仅使用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) 
+0

对不起,花了我很长的时间才找到你,它完美的作品。我花了几分钟的时间来解析这个循环! (我的意思是解析它,我的电脑真的很快。) – prooffreader