python - pandas.DataFrame 子类的属性在 pickle 后消失

标签 python class inheritance subclass pandas

我正在尝试向 pandas.DataFrame 的子类添加属性,它们在酸洗和解酸洗后消失了:

import cPickle
import pandas as pd

class MyClass(pd.DataFrame):
    def __init__(self):
        super(MyClass, self).__init__()
        self.bar = 1

myc = MyClass()
with open('myc.pickle', 'wb')as myfile:
    cPickle.dump(myc,myfile)
with open('myc.pickle', 'rb')as myfile:
    b = cPickle.load(myfile)
print b.bar

输出:

Traceback (most recent call last):
File "test_df.py", line 14, in <module>
print b.bar
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1771, in __getattr__
(type(self).__name__, name))
AttributeError: 'MyClass' object has no attribute 'bar'

知道如何安全地添加属性吗?

最佳答案

这与子类化无关。 Pandas 对象的属性不会序列化。

您可以阅读 this thread进行讨论和解决方法。该话题在 this other recent thread 中再次浮出水面.

关于python - pandas.DataFrame 子类的属性在 pickle 后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250499/

相关文章:

class - 如何处理类内部的多态性

python - 将支持功能放在类中的最佳位置在哪里?

c++ - 使用语法在派生类中公开基类别名模板和变量模板?

python - python 中的类出现问题

python - 在Python中迭代数组时添加数组中的当前元素+数组中的下一个元素

java - 我似乎不太理解 super() 关键字及其用法

c++ - 如何为派生类通用地实现复制构造函数?

java - 如何覆盖从父复杂类型继承的元素类型?

python - 如何使用 sqlalchemy 轻松初始化所有值为 null 的新对象

python - 打开pyxl : need the max number of rows in a column that has data in Excel