【问题标题】:Best way to convert Pandas dataframe to json in python在 python 中将 Pandas 数据帧转换为 json 的最佳方法
【发布时间】:2014-12-27 04:53:35
【问题描述】:

我正在尝试将 pandas 数据帧转换为 python 中的 json。但我无法在 json 中获得想要的结果格式,我是 pandas 的新手,有没有一种方法可以旋转并简单地使用所有我能想到的就是一遍又一遍地创建循环来获取关键的“频率”和状态。但我觉得必须有更好的方法。任何建议将不胜感激。

json:我想要:

 [
    {State:'AL',freq:{low:4786, mid:1319, high:249}}
    ,{State:'AZ',freq:{low:1101, mid:412, high:674}}
    ,{State:'CT',freq:{low:932, mid:2149, high:418}}
    ,{State:'DE',freq:{low:832, mid:1152, high:1862}}
    ,{State:'FL',freq:{low:4481, mid:3304, high:948}}
    ,{State:'GA',freq:{low:1619, mid:167, high:1063}}
    ,{State:'IA',freq:{low:1819, mid:247, high:1203}}
    ,{State:'IL',freq:{low:4498, mid:3852, high:942}}
    ,{State:'IN',freq:{low:797, mid:1849, high:1534}}
    ,{State:'KS',freq:{low:162, mid:379, high:471}}
    ];

但我的数据框有 3 个这样的列:

数据框:我得到了

State   type    freq
AZ  low 1101
CT  low 932
DE  low 832
FL  low 4481
GA  low 1619
IA  low 1819
IL  low 4498
IN  low 797
KS  low 162
AZ  mid 412
CT  mid 2149
DE  mid 1152
FL  mid 3304
GA  mid 167
IA  mid 247
IL  mid 3852
IN  mid 1849
KS  mid 379
AZ  high    674
CT  high    418
DE  high    1862
FL  high    948
GA  high    1063
IA  high    1203
IL  high    942
IN  high    1534
KS  high    471

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:
    import pandas as pd
    
    data = """\
    State   type    freq
    AZ  low 1101
    CT  low 932
    DE  low 832
    FL  low 4481
    GA  low 1619
    IA  low 1819
    IL  low 4498
    IN  low 797
    KS  low 162
    AZ  mid 412
    CT  mid 2149
    DE  mid 1152
    FL  mid 3304
    GA  mid 167
    IA  mid 247
    IL  mid 3852
    IN  mid 1849
    KS  mid 379
    AZ  high    674
    CT  high    418
    DE  high    1862
    FL  high    948
    GA  high    1063
    IA  high    1203
    IL  high    942
    IN  high    1534
    KS  high    471"""
    
    data = pd.DataFrame([line.split() for line in data.splitlines()[1:]],
                        columns=data.splitlines()[0].split())
    
    bystate = data.pivot('State', 'type')
    

    打印

              freq            
       type   high   low   mid
       State                  
       AZ      674  1101   412
       CT      418   932  2149
       DE     1862   832  1152
       FL      948  4481  3304
       GA     1063  1619   167
       IA     1203  1819   247
       IL      942  4498  3852
       IN     1534   797  1849
       KS      471   162   379
    

    获得最终数据框后,您可以使用bystate.to_json() 获取 JSON 格式的字符串。

    【讨论】:

    • OP 需要 JSON 输出。只需添加bystate.json
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2018-03-13
    • 2018-10-27
    • 2019-06-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多