Yariv
Yariv

Reputation: 13321

How to add attributes to a subclass of pandas.DataFrame?

I would like to add attributes to a subclass of DataFrame, but I get an error:

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


RuntimeError: maximum recursion depth exceeded

Upvotes: 5

Views: 2080

Answers (2)

Calvin Cheng
Calvin Cheng

Reputation: 36506

In [12]: class Foo(pd.DataFrame):
   ....:     def __init__(self, bar=None):
   ....:         super(Foo, self).__init__()
   ....:         self.bar = bar      

which results in:-

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   

Upvotes: 1

Andy Hayden
Andy Hayden

Reputation: 375485

You want to write this as follows:

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

See the Python's __init__ syntax question.

Upvotes: 2

Related Questions