【问题标题】:Catch pandas df.to_json() exception捕捉 pandas df.to_json() 异常
【发布时间】:2018-03-28 23:57:29
【问题描述】:

我正在尝试确定执行 pandas DataFrame.to_json() 方法时失败的原因。 DataFrame 是有效的,但它非常大(大约 1,000,000 条记录)。

这是我的代码,predictions 是我的 DataFrame:

try:
    predictions.to_json(write_file, orient='records', lines=True)
except EOFError as eoferr:
    print(eoferr)
    sys.exit('\nUnable to write file (%s)! EOFError. Exiting...' % write_file)
except IOError as ioerr:
    print(ioerr)
    sys.exit('\nUnable to write file (%s)! Permissions problem Exiting...' % write_file)
except Exception as e:
    print(e)
    sys.exit('\nUnable to write file (%s)! Unknown exception. Exiting...' % write_file)

现在,我收到了 Unknown exception. Exiting... 异常。提前致谢!

【问题讨论】:

  • 可以尝试遍历行并在每一行上调用 to_json 吗?
  • 谢谢@mobone——我想出了一个解决方法并将其发布为答案。

标签: python json pandas dataframe exception


【解决方案1】:

不是解决方案,而是解决方法

相信这是DataFrame.to_json() 的内存问题——机器在尝试将大约 5M 记录 x 1000 列的 DataFrame 转换为 JSON 文件时会挂起,并退出引发一般@ 987654322@.

解决方法是使用DataFrame.to_dict(),然后使用json.dump()

import json

write_file = "/path/to/output.json"
holder_dictionary = predictions.to_dict(orient='records')

with open(write_file, 'w') as outfile:
    json.dump(holder_dictionary, outfile)

这适用于(到目前为止)任何大小的 DataFrame。同时,我将在 Pandas 存储库中提交错误/问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-10
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多