首页 > 解决方案 > 使用 pandas read_json 导入文件时遇到问题

问题描述

我是 Python 新手(我使用的是 python 3),我正在尝试在 Jupyter 笔记本中导入 JSON 文件。但是,它给出了以下错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 4276350: character maps to <undefined> 

下面是代码:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as plt
import json
%matplotlib inline

with open('C:\\Users/Desktop/Machine  Learning/yelp_academic_dataset_business.json') as datafile:
data = pd.read_json(datafile,orient='columns',encoding='utf-8')
dataframe = pd.DataFrame(data)

我将不胜感激任何帮助。

标签: jsonpython-3.xpandasjupyter-notebook

解决方案


假设是您要导入的文件,它实际上是许多 JSON 对象,每行一个。您需要通过指定逐行导入它lines=True

data = pd.read_json(datafile, lines=True, orient='columns', encoding='utf-8')

此外,将文件路径作为第一个参数传递,而不是文件内容。您可以摆脱打开文件的代码。此外,pd.read_json返回一个 DataFrame,不需要程序的最后一行:

>>> data = pd.read_json('yelp_academic_dataset_business.json', lines=True, orient='columns', encoding='utf-8')
>>> data
                                              attributes             business_id                                         categories             city    ...    review_count stars  state      type
0      {'Take-out': False, 'Wi-Fi': 'free', 'Good For...  O_X3PGhk3Y5JWVi866qlJg  [Active Life, Arts & Entertainment, Stadiums &...          Phoenix    ...              29   4.0     AZ  business
1      {'Parking': {'garage': False, 'street': False,...  QbrM7wqtmoNncqjc6GtFaQ  [Tires, Automotive, Fashion, Shopping, Departm...         Glendale    ...               3   3.5     AZ  business

推荐阅读