Keumes
Keumes

Reputation: 59

Passing metadata when slicing subclass of DataFrame

I've created a class which inherits from pandas.DataFrame. In this class metadata is added (not to columns, but to the class instance):

class MeasurementPoint(pandas.DataFrame):

    def __init__(self, data, metadata):
        super(MeasurementPoint, self).__init__(data)
        self.metadata = metadata

    # in order to return MeasurementPoint instead of DataFrame, define _constructor
    def _constructor(self):
        return MeasurementPoint

If I slice the class, I get a TypeError since __init__ is missing the required argument metadata. I've tried to modify _constructor to pass the metadata, but without succes. I've also tried to add the metadata to the class as an additional property (_metadata' = ['metadata']) as described here: http://pandas.pydata.org/pandas-docs/stable/internals.html, but to no avail.

How can I get the class MeasurementPoint to retain the metadata when it's being sliced?

Upvotes: 3

Views: 244

Answers (1)

Keumes
Keumes

Reputation: 59

Not sure whether it's considered good form to answer your own questions, but the following seems to work:

class MeasurementPoint(pandas.DataFrame):

    _metadata = ['metadata']

    def __init__(self, *args, **kwargs):
        metadata = kwargs.pop('metadata', {})
        super(MeasurementPoint, self).__init__(*args, **kwargs)
        self.metadata = metadata

    @property
    def _constructor(self):
        return MeasurementPoint

Upvotes: 2

Related Questions