在熊猫中将数据框列表作为json文件导出和导入

时间:2019-07-20 00:24:30

标签: python pandas

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文件,其中所有数据框均转换为字典。但是,当我尝试相反操作以读取文件并提取我的数据框时,出现错误。这是代码:

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

我得到的错误是: JSONDecodeError:额外数据

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

1 个答案:

答案 0 :(得分:1)

通过使用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())]