【问题标题】:pandas long-form table to nested json熊猫长表到嵌套的json
【发布时间】:2014-05-02 16:53:51
【问题描述】:

我浏览了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

我需要一个格式如下的 JSON 文件:

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

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

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

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

    【讨论】:

    • 对不起,我花了这么长时间才回复你,它工作得很好。我花了几分钟来解析那个循环! (我的意思是让我的大脑解析它,我的电脑做得非常快。)
    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 2014-08-13
    • 2018-05-05
    • 2017-11-28
    • 2017-03-28
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多