0

I want to define a class which does not inherit from pandas.DataFrame but sometimes acts like it. For example, I can do:

import pandas
import numpy

class FalseDF(object):
    def __init__(self, df):
        self.df = df

    def __getitem__(self, item):
        return self.df.__getitem__(item)


df = pandas.DataFrame(numpy.reshape(numpy.arange(10), (2, 5)))
print(df)

which gives:

   0  1  2  3  4
0  0  1  2  3  4
1  5  6  7  8  9

and now:

fdf = FalseDF(df)
print(fdf[3])

gives:

0    3
1    8
Name: 3, dtype: int64    

How can I now make the following syntax also work?

    print(fdf.iloc[1])

or

    print(fdf.loc[2])

1 Answer 1

1

It might not capture all the behavior of a DataFrame, but for starters you could implement __getattr__ or, much more risky, __getattribute__ to pass on requests for attributes to the underlying dataframe:

class FalseDF:
    def __getattr__(self, key):
        return getattr(self.df, key)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.