[英]Catch pandas df.to_json() exception
我试图确定执行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...
正在Unknown exception. Exiting...
正在引发异常。 提前致谢!
不是解决方案 ,而是解决方法 。
我认为这是DataFrame.to_json()
的内存问题-机器将挂起,尝试将约5M条记录x 1000列的DataFrame转换为JSON文件,然后退出并引发一般Exception
。
解决方法是使用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。 同时,我将在熊猫存储库上提交错误/问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.