Extending pandas: astype changes DataFrame class type

Viewed 30

When inheriting from pd.DataFrame it is not clear to me why astype() changes the result back to pd.DataFrame rather than the new type subclassing pd.DataFrame? Is there a @property I can define similar to _constructor to make sure that df.astype() returns the correct type?

docs: https://pandas.pydata.org/docs/development/extending.html

import pandas as pd

class DF(pd.DataFrame):
    @property
    def _constructor(self):
        return self.__class__


df = DF({
    'A': [1,2,3],
    'B': [10,20,30],
    'C': [100,200,300],
})  # Type is DF


a = df['A'] # type is Series
ab = df[['A', 'B']] # type is DF

dtypes = {'A': 'float64', 'B': 'float64', 'C': 'float64'}
x = df.astype(dtypes)

type(x)  # type is pd.DataFrame
0 Answers
Related