【问题标题】:Reading JSON formatted file into pandas DataFrame将 JSON 格式的文件读入 pandas DataFrame
【发布时间】:2019-12-12 19:39:12
【问题描述】:

我想将 JSON 格式化程序文件读入 pandas DataFrame,将数据集组织成行和列。我附上了我的 JSON 文件中数据的样子的图片。原始数据有 2010/01/01 到 2010/01/30 的 30 天每日温度数据。

Raw JSON data in the input file '09386950_NM_USGS_TOBS.json':

[{
    'beginDate': '2010-01-01 00:00:00',
    'collectionDates': [],
    'duration': 'DAILY',
    'endDate': '2010-01-30 00:00:00',
    'flags': [],
    'stationTriplet': '302:OR:SNTL',
    'values': [
        Decimal('31.820'),
        Decimal('27.140'),
        Decimal('14.900'),
        Decimal('35.600'),
        Decimal('34.340'),
        Decimal('31.100'),
        Decimal('9.140'),
        Decimal('21.380'),
        Decimal('36.140'),
        Decimal('28.040'),
        Decimal('35.960'),
        Decimal('34.700'),
        Decimal('28.040'),
        Decimal('25.160'),
        Decimal('33.980'),
        Decimal('31.640'),
        Decimal('31.640'),
        Decimal('29.300'),
        Decimal('29.120'),
        Decimal('25.880'),
        Decimal('24.980'),
        Decimal('21.740'),
        Decimal('18.320'),
        Decimal('20.480'),
        Decimal('26.780'),
        Decimal('28.940'),
        Decimal('24.440'),
        Decimal('15.440'),
        Decimal('21.020'),
        Decimal('31.820')
    ]
}]

我试过的代码如下:

import pandas as pd
import json
with open(r'C:\Users\Anurag.Srivastava\Downloads\09386950_NM_USGS_TOBS.json', 'r') as f:
    data = json.load(f)
    df = pd.DataFrame(data)

我得到的错误信息是:

Traceback (most recent call last):

  File "<ipython-input-54-2d2966de6f43>", line 1, in <module>
    runfile('C:/Users/Anurag.Srivastava/Downloads/Learing_pandas.py', wdir='C:/Users/Anurag.Srivastava/Downloads')

  File "C:\Users\Anurag.Srivastava\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Anurag.Srivastava\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Anurag.Srivastava/Downloads/Learing_pandas.py", line 63, in <module>
    data = json.load(f)

  File "C:\Users\Anurag.Srivastava\anaconda3\lib\json\__init__.py", line 296, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

  File "C:\Users\Anurag.Srivastava\anaconda3\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)

  File "C:\Users\Anurag.Srivastava\anaconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())

  File "C:\Users\Anurag.Srivastava\anaconda3\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)

JSONDecodeError: Expecting property name enclosed in double quotes

【问题讨论】:

  • JSON uses double quotes, not single quotes。这不是格式正确的 JSON。为了使其格式正确,您可以尝试将单引号批量替换为双引号,这可能会起作用,具体取决于您的数据。如果是手动写入的数据,用双引号重新写入。如果没有,则必须进行替换转换。
  • 感谢您的 cmets。我是学习处理 JSON 文件的新手,所以对引号一无所知。

标签: json python-3.x pandas dataframe


【解决方案1】:

为了使 Python 能够将文件视为 json,需要将单引号替换为双引号,并且需要清理 Decimal() 符号。您可以执行以下操作:

import pandas as pd
import json
with open(file_name) as f:
    s = f.read()
    s = s.replace("'", '"')
    s = s.replace('Decimal("', '')
    s = s.replace('")', '')
    data = json.loads(s)
    for item in data:
        df = pd.DataFrame(item)

然后可能会创建一个索引并附加相应的值,例如:

idx = pd.date_range(item['beginDate'], item['endDate'])
df = pd.DataFrame(idx)
df['values'] = item['values']

【讨论】:

  • 这很好用。唯一的问题是最后一行“ df['values'] = data['values'] ”,我收到一个错误“列表索引必须是整数或切片,而不是str”。可能与访问字典中的列表有关。
  • data是一个对象列表,因为json是一个列表,所以需要进行相应的迭代。我调整了答案。
  • 我发现对代码的修改工作正常: beginDate='2010-01-01' endDate='2010-01-30' 和 open('09386950_NM_USGS_TOBS.json', 'r') as f: s = f.read() s = s.replace("'", '"') s = s.replace('Decimal("', '') s = s.replace('")', ' ') 数据 = json.loads(s) f.close() idx = pd.date_range(start=beginDate, end=endDate) df = pd.DataFrame(idx) df['values'] = data[0]['值']
【解决方案2】:

该文件不是有效的 JSON 数据,因此解析器无法正确检测对象。像这样使用任何在线 JSON 验证器:https://jsonlint.com/ 一旦你修复了 JSON。我还建议您使用

pd.read_json(<Path>)

这种方法将以正确的方式创建数据帧。

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 2018-06-23
    • 1970-01-01
    • 2022-01-07
    • 2022-01-13
    • 2016-08-18
    • 2016-02-22
    • 2021-11-24
    • 2019-06-08
    相关资源
    最近更新 更多