【问题标题】:Pandas DataFrame to Json schemaPandas DataFrame 到 Json 模式
【发布时间】:2021-09-17 08:38:29
【问题描述】:

我有以下数据框,但不确定如何将其转换为有用的 Json 输出。

Name     Id    Qty   Value
thing1   123   10    12.5
thing2   456   20    15.4
thing3   789   40    84.2

我目前正在使用to_json(),但我有点不确定如何使用它来生成以下 json 架构。我想要

{"Name":"thing1"
 "Id":123,
 "Quantity":10, 
 "Value":12.5
 },
{"Name":"thing2"
 "Id":456,
 "Quantity":20, 
 "Value":15.4
 },
{"Name":"thing3"
 "Id":789,
 "Quantity":40, 
 "Value":84.2
 },

我现在可以使用的解决方案

out=df.reset_index().to_json(orient='record')

【问题讨论】:

  • 你可以试试:df.to_json(orient='records')
  • 也许你的Nameid 是索引?试试:df.reset_index().to_json(orient='records') ?
  • df.to_dict("records")
  • 谢谢大家! reset_index 成功了。
  • @RobRaymond to_dict()to_json() 的输出略有不同。 to_dict() 给出单引号输出,而to_json() 给出双引号,这似乎更符合 OP 的要求。

标签: python json pandas


【解决方案1】:

.to_jsonorient="records" 参数一起使用:

import json
parsed = json.loads
result = df.to_json(orient="records")
parsed = json.loads(result)
json_out = json.dumps(parsed, indent=4)
print(json_out)

【讨论】:

    【解决方案2】:

    使用 orient 参数。

    ‘split’ : dict 像 {‘index’ -> [index], ‘columns’ -> [columns], ‘数据’ -> [值]}

    ‘records’ : 类似 [{column -> value}, ... , {column -> value}] 的列表]

    'index' : dict 像 {index -> {column -> value}}

    'columns' : dict 像 {column -> {index -> value}}

    ‘values’:只是值数组

    ‘table’: dict 像 {‘schema’: {schema}, ‘data’: {data}}

    import pandas as pd
    import json
    df = pd.DataFrame(columns=['Name', 'Id', 'Qty', 'Value'])
    df['Name'] = ['thing1', 'thing2', 'thing3']
    df['Id'] = [123, 456, 789]
    df['Qty'] = [10, 20, 40]
    df['Value'] = [12.5, 15.4, 84.2]
    data = df.to_json(orient='records')
    json.loads(data)
    

    输出:

    [{'Name': 'thing1', 'Id': 123, 'Qty': 10, 'Value': 12.5},
     {'Name': 'thing2', 'Id': 456, 'Qty': 20, 'Value': 15.4},
     {'Name': 'thing3', 'Id': 789, 'Qty': 40, 'Value': 84.2}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 2019-11-14
      • 2021-10-23
      • 2017-01-08
      • 2018-06-09
      • 1970-01-01
      • 2014-11-02
      相关资源
      最近更新 更多