json - 使用 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)
我将不胜感激任何帮助。
解决方案
假设这是您要导入的文件,它实际上是许多 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
推荐阅读
- python - 如何从 Markdown 文件创建树?
- jquery - 在 Django 中使用 jQuery 和 AJAX 动态更新 Web API 结果
- twos-complement - 二进制补码加法。-48 - 23. 是否必须使用 8 位表示?
- react-native - Redux Saga action 异步操作调用了一次但触发了两次
- java - Maven 上的未知生命周期阶段
- amazon-web-services - 了解服务器/客户端路由:亚马逊(?)如何在没有重定向(或历史条目)的情况下重定向我的 SPA?
- c - 编译器或处理器在运行时如何区分静态局部变量?
- python - 如何查找特定频道的 forUsername 参数
- linux - 有没有不使用getppid就可以找到父进程的PID?
- python - 熊猫从表中删除索引