首页 > 解决方案 > 在 Pandas 中将数据框列表导出和导入为 json 文件

问题描述

Pandas 具有适用于单个数据框的 DataFrame.to_json 和 pd.read_json 函数。但是,我一直在尝试找到一种方法来将包含许多数据框的列表导出和导入单个 json 文件。到目前为止,我已经使用以下代码成功导出列表:

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

这将创建一个 json 文件,其中所有数据帧都转换为 dicts。但是,当我尝试反向读取文件并提取我的数据框时,出现错误。这是代码:

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

我得到的错误是: JSONDecodeError: Extra data

我认为问题在于我必须以某种方式在读取 json 文件的代码中包含与“writelines”相反的内容,即“readlines”,但我不知道该怎么做。任何帮助将不胜感激!

标签: pythonpandas

解决方案


通过使用writelines您的数据并不是真正意义上的 Python 列表,这使得阅读它有点棘手。我建议改为这样写入您的文件:

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

这意味着我们可以像简单地使用一样读取它:

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

推荐阅读