【问题标题】:Exporting and Importing a list of Data Frames as json file in Pandas在 Pandas 中将数据框列表导出和导入为 json 文件
【发布时间】:2019-07-20 09:06:10
【问题描述】:

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: 额外数据

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

【问题讨论】:

    标签: python pandas


    【解决方案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())]
    

    【讨论】:

    • 我在加载 json 文件以读取它时遇到了一个奇怪的问题。 DataFrames 是按字母顺序索引的,这很不方便。你知道这是为什么吗?
    • 根据你的 python 版本,dict 可能不能保证与创建它的顺序相同。我不确定 pandas 是否可以返回 orderdict,但你可能想看看保持索引。 outfile 是什么样的?
    • outfile json 按需要排序。实际上,这是 Pandas 中的一个错误,可以通过操作 'orient=index' 然后执行转置来解决。这使索引保持在其原始位置,但改变了列的顺序,必须重新排序。在这里,更多信息:github.com/pandas-dev/pandas/issues/8425
    猜你喜欢
    • 2019-10-13
    • 2012-12-11
    • 2016-07-06
    • 2023-04-05
    • 2019-09-01
    • 1970-01-01
    • 2022-12-07
    • 2014-12-27
    • 2022-10-04
    相关资源
    最近更新 更多