如何向pandas.DataFrame的子类添加属性?

如何向pandas.DataFrame的子类添加属性?,pandas,Pandas,我想向DataFrame的子类添加属性,但出现了一个错误: >>> import pandas as pd >>>class Foo(pd.DataFrame): ... def __init__(self): ... self.bar=None ... >>> Foo() RuntimeError: maximum recursion depth exceeded 您希望这样写: class

我想向DataFrame的子类添加属性,但出现了一个错误:

>>> import pandas as pd
>>>class Foo(pd.DataFrame):
...     def __init__(self):
...         self.bar=None
...         
>>> Foo()


RuntimeError: maximum recursion depth exceeded

您希望这样写:

class Foo(pd.DataFrame):
  def __init__(self):
    super(Foo, self).__init__()
    self.bar = None
请看问题

其结果是:-

In [30]: my_special_dataframe = Foo(bar=1)

In [31]: my_special_dataframe.bar
Out[31]: 1

In [32]: my_special_dataframe2 = Foo() 

In [33]: my_special_dataframe2.bar   

虽然下面解决了这个问题,但从这个问题引出的有趣的事情是,为什么存在最大递归深度异常,与
数据帧有关。\uuuu getattr\uuuu
…就像一个指针:此解决方案将使您在pickle Foo时遇到麻烦,因为您正在设置self.bar=None您实际上设置了pandas属性,而pandas属性不会被pickle。因此,基本上您将从Foo中释放所有添加的属性。目前还不支持DataFrame的“适当”子类化,请参阅,但正在取得进展。为仅供参考,为DataFrame创建了一个可拾取的子类,该子类具有自定义属性元数据:。另一种更丑陋的可能性是使用DataFrame.name作为属性,因为这是数据帧中唯一被pickle的“元数据”。
In [30]: my_special_dataframe = Foo(bar=1)

In [31]: my_special_dataframe.bar
Out[31]: 1

In [32]: my_special_dataframe2 = Foo() 

In [33]: my_special_dataframe2.bar