title: How can I subclass a Pandas DataFrame?
body: <p>Subclassing Pandas classes seems a common need, but I could not find references on the subject. (It seems that Pandas developers are still working on it: <em><a href="https://github.com/pydata/pandas/issues/60" rel="nofollow noreferrer">Easier subclassing #60</a></em>.)</p>
  <p>There are some SO questions on the subject, but I am hoping that someone here can provide a more systematic account on the current best way to subclass <code>pandas.DataFrame</code> that satisfies two general requirements:</p>
  <ol>
  <li>calling standard DataFrame methods on instances of MyDF <strong>should produce instances of MyDF</strong></li>
  <li>calling standard DataFrame methods on instances of MyDF <strong>should leave all attributes still attached to the output</strong></li>
  </ol>
  <p>(And are there any significant differences for subclassing <em>pandas.Series</em>?)</p>
  <p>Code for subclassing <code>pd.DataFrame</code>:</p>
  <pre><code>import numpy as np
  import pandas as pd
  
  class MyDF(pd.DataFrame):
      # how to subclass pandas DataFrame?
      pass
  
  mydf = MyDF(np.random.randn(3,4), columns=['A','B','C','D'])
  print(type(mydf))  # &lt;class '__main__.MyDF'&gt;
  
  # Requirement 1: Instances of MyDF, when calling standard methods of DataFrame,
  # should produce instances of MyDF.
  mydf_sub = mydf[['A','C']]
  print(type(mydf_sub))  # &lt;class 'pandas.core.frame.DataFrame'&gt;
  
  # Requirement 2: Attributes attached to instances of MyDF, when calling standard
  # methods of DataFrame, should still attach to the output.
  mydf.myattr = 1
  mydf_cp1 = MyDF(mydf)
  mydf_cp2 = mydf.copy()
  print(hasattr(mydf_cp1, 'myattr'))  # False
  print(hasattr(mydf_cp2, 'myattr'))  # False
  </code></pre>