将JSON文件读取为 pandas 数据框? [英] Read json file as pandas dataframe?
本文介绍了将JSON文件读取为 pandas 数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用python 3.6并尝试使用以下代码将json文件(350 MB)下载为pandas数据帧.但是,出现以下错误:
I am using python 3.6 and trying to download json file (350 MB) as pandas dataframe using the code below. However, I get the following error:
data_json_str = "[" + ",".join(data) + "]
"TypeError: sequence item 0: expected str instance, bytes found
如何解决该错误?
import pandas as pd
# read the entire file into a python array
with open('C:/Users/Alberto/nutrients.json', 'rb') as f:
data = f.readlines()
# remove the trailing "\n" from each line
data = map(lambda x: x.rstrip(), data)
# each element of 'data' is an individual JSON object.
# i want to convert it into an *array* of JSON objects
# which, in and of itself, is one large JSON object
# basically... add square brackets to the beginning
# and end, and have all the individual business JSON objects
# separated by a comma
data_json_str = "[" + ",".join(data) + "]"
# now, load it into pandas
data_df = pd.read_json(data_json_str)
推荐答案
如果以二进制文件('rb'
)打开文件,则将获得字节.怎么样:
If you open the file as binary ('rb'
), you will get bytes. How about:
with open('C:/Users/Alberto/nutrients.json', 'rU') as f:
这篇关于将JSON文件读取为 pandas 数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文