gpt4 book ai didi

python - 无法解开从 pandas DataFrame 继承的类

转载 作者:行者123 更新时间:2023-11-28 18:56:56 29 4
gpt4 key购买 nike

我正在尝试挑选从 pandas.DataFrame 继承的对象。我添加到数据框的属性在 pickling/unpickling 过程中消失了。有一些明显的解决方法,但是......我做错了什么,还是这是一个错误?

import pandas as pd
import pickle

class Foo(pd.DataFrame):
def __init__(self,tag,df):
super().__init__(df)
self._tag = tag

foo = Foo('mytag', pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}))
print(foo)
print(foo._tag)

print("-------------------------------------")

with open("foo.pkl", "wb") as pkl:
pickle.dump(foo, pkl)

with open("foo.pkl", "rb") as pkl:
foo1 = pickle.load(pkl)

print(type(foo1))
print(foo1)
print(foo1._tag)

这是我的输出:

   a  b
0 1 4
1 2 5
2 3 6
mytag
-------------------------------------
<class '__main__.Foo'>
a b
0 1 4
1 2 5
2 3 6
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-20-1e7e89e199c8> in <module>
21 print(type(foo1))
22 print(foo1)
---> 23 print(foo1._tag)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):

AttributeError: 'Foo' object no attribute '_tag'

(python 3.7,pandas 0.24.2,pickle.format_version 4.0)

最佳答案

Michael 的回答与我在查看他们的代码时的发现相符。 DataFrame 继承自 NDFrame,后者也覆盖了 __setattr__,因此这也可能导致此问题。

这里最直接的解决方案是创建一个使用数据框作为属性的类,以便您可以设置自己的属性。

class Foo:
def __init__(self, tag, df):
self.df = df
self._tag = tag

*此外:如果 native pickle 无法 pickle 像这样的复杂对象,我会考虑尝试 dill$ pip install dill 之后,您需要做的就是import dill as pickle,因为它的方法名称与pickle 相同。

关于python - 无法解开从 pandas DataFrame 继承的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237664/

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