Skip to content

Subclass of DataFrame losing properties on arithmetic functions like __add__ #19376

@akashgurava

Description

@akashgurava
class PDMixIn(object):

    @property
    def _constructor(self):
        return self.__class__

class DF(PDMixIn, pd.DataFrame):
    _metadata = ['my_prop']

    def __init__(self, *args, **kwargs):
        my_prop = kwargs.pop('my_prop', 'some_prop')
        super().__init__(*args, *kwargs)
        self.my_prop = my_prop

df = DF(my_prop='new_prop')
print(df.my_prop)
# 'new_prop' 

# But after adding 1
df = df + 1
print(df.my_prop)
# 'some_prop'

Seems like DF is losing property value after addition I found similar behaviour for sub and others.

I was able to solve the problem by adding following code to PDMixIn

def __add__(self, other):
        result = pd.DataFrame.__add__(self, other)
        return self._constructor(result).__finalize__(self)

df = df + 1
print(df.my_prop)
# 'new_prop'

INSTALLED VERSIONS

commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: None.None

pandas: 0.22.0
pytest: 3.3.0
pip: 9.0.1
setuptools: 36.5.0.post20170921
Cython: 0.27.3
numpy: 1.13.3
scipy: 1.0.0
pyarrow: None
xarray: None
IPython: 6.2.1
sphinx: 1.6.3
patsy: 0.4.1
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: 1.2.1
tables: 3.4.2
numexpr: 2.6.4
feather: None
matplotlib: 2.1.1
openpyxl: 2.4.9
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 1.0.2
lxml: 4.1.1
bs4: 4.6.0
html5lib: 1.0.1
sqlalchemy: 1.1.13
pymysql: None
psycopg2: 2.7.3.2 (dt dec pq3 ext lo64)
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Duplicate ReportDuplicate issue or pull requestSubclassingSubclassing pandas objects

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions