【问题标题】:How to convert this DataFrame into Json如何将此 DataFrame 转换为 Json
【发布时间】:2021-04-07 18:21:33
【问题描述】:

我有这个DataFrame 2 列

print(df)

     a                b

     10          {'A': 'foo', ...}
     20          {'B': 'faa', ...}
     30          {'C': 'fee', ...}
     40          {'D': 'fii', ...}
     50          {'E': 'foo', ...}

当我尝试将其转换为 json 时出错:

df.to_json("test.json")

# Output:


{
"a":{10, 20, 30, 40, 50},
"b":{
   "1":{
      "A":"foo",
      ...
      },
   "2":{
      "B":"faa",
      ...
      },
   "3":{
      "B":"faa",
      ...
      },

   ... 

   "5":{
      "E":"foo",
      ...
      }
}

我什至不知道这些数字是从哪里来的。

我想要的json:

[{
   'a': 10,
   'b': {
         'A': 'foo', 
         ...
        }, 
    ...
    'a': 50,
    'b': {
         'E': 'foo', 
         ...
        }
}
]

【问题讨论】:

  • 您想要的输出不是有效的 JSON 对象。
  • 哪种形式最接近它? PD:为什么不是有效格式?
  • df.to_json("test.json", orient='records')?
  • 我也试过了,但输出还是一样
  • 不在我这边,那会给[{"a":10, "b":{"A":"foo"} } , {"a":20, "b":{"B":"bar"} }, ....]。

标签: python json pandas dataframe


【解决方案1】:

您可以尝试以下方法:

data = []
for i in df:
    data.append({'a': df[i[0]], 'b': df(i[1])})

这应该会给你想要的输出。

如果您想将其转换为 JSON 文件,则可以执行以下操作:

with open("myjson.json", "w") as f:
    json.dump(data, f, indent=4)

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2019-08-15
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2017-04-13
    • 2021-03-29
    相关资源
    最近更新 更多