简体   繁体   English

在 Pandas 中将数据帧列表导出和导入为 json 文件

[英]Exporting and Importing a list of Data Frames as json file in Pandas

Pandas has the DataFrame.to_json and pd.read_json functions that work for single Data Frames. Pandas 具有适用于单个数据帧的 DataFrame.to_json 和 pd.read_json 函数。 However, I have been trying to figure a way to export and import a list with many Data Frames into and from a single json file.但是,我一直在尝试找到一种方法,将包含许多数据帧的列表导出到单个 json 文件中,并将其导入到单个 json 文件中。 So far, I have come to successfully export the list with this code:到目前为止,我已经使用此代码成功导出列表:

with open('my_file.json', 'w') as outfile:
    outfile.writelines([json.dumps(df.to_dict()) for df in list_of_df])

This creates a json file with all the Data Frames converted to dicts.这将创建一个 json 文件,其中所有数据帧都转换为 dicts。 However, when I try to do the reverse to read the file and extract my Data Frames, I get an error.但是,当我尝试反向读取文件并提取数据帧时,出现错误。 This is the code:这是代码:

with open('my_file.json', 'r') as outfile:
    list_of_df = [pd.DataFrame.from_dict(json.loads(item)) for item in 
    outfile]

The error I get is: JSONDecodeError: Extra data我得到的错误是:JSONDecodeError: Extra data

I think the problem is that I have to include somehow the opposite of 'writelines', which is 'readlines' in the code that reads the json file, but I do not know how to do it.我认为问题在于我必须以某种方式包含与“writelines”相反的内容,即读取 json 文件的代码中的“readlines”,但我不知道该怎么做。 Any help will be appreciated!任何帮助将不胜感激!

By using writelines your data isn't really a list in the python sense, which makes reading it a bit tricky.通过使用writelines您的数据在 Python 意义上并不是真正的列表,这使得读取它有点棘手。 I'd recommend instead writing to your file like this:我建议改为像这样写入您的文件:

with open('my_file.json', 'w') as outfile:
    outfile.write(json.dumps([df.to_dict() for df in list_of_df]))

Which means we can read it back just as simply using:这意味着我们可以简单地使用:

with open('my_file.json', 'r') as outfile:
    list_of_df = [pd.DataFrame.from_dict(item) for item in json.loads(outfile.read())]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM