【问题标题】:Reading JSON in a format that can be plotted以可以绘制的格式读取 JSON
【发布时间】:2021-01-14 00:08:30
【问题描述】:

我想读取从dict() 生成的 JSON 文件,然后我可以制作饼图。到目前为止我的代码:

import json
import pandas as pd

openJson = open("path")

jsonFile = json.load(openJson)

df = pd.DataFrame.from_dict(jsonFile)

我遇到的问题是我什至无法尝试绘制图表,因为我无法将 JSON 转换为数据框。我得到的错误是ValueError: If using all scalar values, you must pass an index。我也尝试过写df = pd.DataFrame.from_dict(jsonFile, index=[0]),如在类似帖子中找到的那样,但似乎index 是一个意外的论点。

如何读取该 JSON 以便对其进行绘图?

LE:添加了名为 category.json 的 JSON 文件

{"Restaurants": 678.7800000000001, "Utilities": 807.26, "Services": 35.67, "Transport": 1295.65, "Shopping": 1454.15, "Groceries": 1162.89}

【问题讨论】:

  • Json 长什么样子
  • @ifly6 我已经编辑了我的帖子以添加文件

标签: python pandas matplotlib


【解决方案1】:

试试下面的

import pandas as pd
import json
with open('data.json') as f:
    df = pd.DataFrame(json.load(f),index=[0])
print(df)

输出

   Restaurants  Utilities  ...  Shopping  Groceries
0       678.78     807.26  ...   1454.15    1162.89

[1 rows x 6 columns]

【讨论】:

【解决方案2】:

像这样读取 JSON 文件

df = pd.read_json (r'C:\Users\XXX\Desktop\data.json')

如果您的文件已经是 JSON 格式,这将起作用。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2019-06-09
  • 1970-01-01
  • 2019-12-16
  • 2018-03-12
相关资源
最近更新 更多