简体   繁体   中英

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

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.

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   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM