gpt4 book ai didi

python - pandas.DataFrame.load/python2 和 python3 之间的保存 : pickle protocol issues

转载 作者:太空狗 更新时间:2023-10-29 22:27:12 25 4
gpt4 key购买 nike

我还没有弄清楚如何使用 pandas DataFrames 在 python 2 和 3 之间进行 pickle 加载/保存。我在 pickler 中有一个“协议(protocol)”选项,但我没有成功玩过,但我希望有人能给我一个快速的想法来尝试。这是获取错误的代码:

python2.7

>>> import pandas; from pylab import *
>>> a = pandas.DataFrame(randn(10,10))
>>> a.save('a2')
>>> a = pandas.DataFrame.load('a2')
>>> a = pandas.DataFrame.load('a3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/pandas-0.10.1-py2.7-linux-x86_64.egg/pandas/core/generic.py", line 30, in load
return com.load(path)
File "/usr/local/lib/python2.7/site-packages/pandas-0.10.1-py2.7-linux-x86_64.egg/pandas/core/common.py", line 1107, in load
return pickle.load(f)
ValueError: unsupported pickle protocol: 3

python 3

>>> import pandas; from pylab import *
>>> a = pandas.DataFrame(randn(10,10))
>>> a.save('a3')
>>> a = pandas.DataFrame.load('a3')
>>> a = pandas.DataFrame.load('a2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.3/site-packages/pandas-0.10.1-py3.3-linux-x86_64.egg/pandas/core/generic.py", line 30, in load
return com.load(path)
File "/usr/local/lib/python3.3/site-packages/pandas-0.10.1-py3.3-linux-x86_64.egg/pandas/core/common.py", line 1107, in load
return pickle.load(f)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf4 in position 0: ordinal not in range(128)

也许期望 pickle 在 python 版本之间工作有点乐观?

最佳答案

我遇到了同样的问题。您可以在 python3 中使用以下函数更改 dataframe pickle 文件的协议(protocol):

import pickle
def change_pickle_protocol(filepath,protocol=2):
with open(filepath,'rb') as f:
obj = pickle.load(f)
with open(filepath,'wb') as f:
pickle.dump(obj,f,protocol=protocol)

那么你应该可以在python2中打开它没有问题。

关于python - pandas.DataFrame.load/python2 和 python3 之间的保存 : pickle protocol issues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14586898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com