【问题标题】:Pandas output to json熊猫输出到 json
【发布时间】:2020-12-21 04:41:07
【问题描述】:

我正在尝试将此 DF 导出到我想要的输出中:

import pandas as pd

data = {'V':  ["0","0","0","0","0","0"],
        'A': ["1","0","1","1","1","0"],
        }

df = pd.DataFrame (data, columns = ['V','A'])

期望的输出:

{"0": {"V": 0,
       "A": 1,
      },
 "1": {"V": 0,
       "A": 0,
     },
...
}

导出为json格式不一样。

df= df.to_json(orient="table")
with open('df.json', 'w') as f:
    f.write(df)

【问题讨论】:

    标签: python json pandas dataframe output


    【解决方案1】:

    df.to_dictorient=index 一起使用:

    In [1672]: x = df.to_dict('index')
    
    In [1672]: x
    Out[1672]: 
    {0: {'V': '0', 'A': '1'},
     1: {'V': '0', 'A': '0'},
     2: {'V': '0', 'A': '1'},
     3: {'V': '0', 'A': '1'},
     4: {'V': '0', 'A': '1'},
     5: {'V': '0', 'A': '0'}}
    

    对于json 输出:

    In [1676]: import json
    
    In [1679]: y = json.dumps(x)
    
    In [1681]: y
    Out[1681]: '{"0": {"V": "0", "A": "1"}, "1": {"V": "0", "A": "0"}, "2": {"V": "0", "A": "1"}, "3": {"V": "0", "A": "1"}, "4": {"V": "0", "A": "1"}, "5": {"V": "0", "A": "0"}}'
    

    编辑:要将值转换为int,请执行以下操作:

    In [1672]: x = df.to_dict('index')
    In [1708]: x = {k: {kk: int(vv) for kk, vv in v.items()} for k, v in x.items()}
    
    In [1710]: y = json.dumps(y)
    
    In [1711]: y
    Out[1711]: '{"0": {"V": 0, "A": 1}, "1": {"V": 0, "A": 0}, "2": {"V": 0, "A": 1}, "3": {"V": 0, "A": 1}, "4": {"V": 0, "A": 1}, "5": {"V": 0, "A": 0}}'
    

    【讨论】:

    • 完美!我只需要转换数字。谢谢你:)
    • 太棒了。你也需要这方面的帮助吗?
    • 不客气。无论如何,为了完成,我已经更新了我的答案,将其转换为int
    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2014-02-01
    相关资源
    最近更新 更多