How to pickle numpy's Inf objects?

冷暖自知 提交于 2019-12-10 20:43:45

问题


When trying to pickle the object Inf as defined in numpy (I think), the dumping goes Ok but the loading fails:

>>> cPickle.dump(Inf, file("c:/temp/a.pcl",'wb'))
>>> cPickle.load(file("c:/temp/a.pcl",'rb'))
Traceback (most recent call last):
  File "<pyshell#257>", line 1, in <module>
    cPickle.load(file("c:/temp/a.pcl",'rb'))
ValueError: could not convert string to float
>>> type(Inf)
<type 'float'>

Why is that? And moreover - is there a way to fix that? I want to pickle something that has Inf in it - changing it to something else will flaw the elegance of the program...

Thanks


回答1:


If you specify a pickle protocol more than zero, it will work. Protocol is often specified as -1, meaning use the latest and greatest protocol:

>>> cPickle.dump(Inf, file("c:/temp/a.pcl",'wb'), -1)
>>> cPickle.load(file("c:/temp/a.pcl",'rb'))
1.#INF                   -- may be platform dependent what prints here.



回答2:


Try this solution at SourceForge which will work for any arbitrary Python object:

y_serial.py module :: warehouse Python objects with SQLite

"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."

http://yserial.sourceforge.net



来源:https://stackoverflow.com/questions/1250367/how-to-pickle-numpys-inf-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!