I am building a script to make a DataFrame I frequently use easily available by mapping it to a class in Python, to no avail.

import pandas as pd

class ImportedDF:

    def __init__(self):

    def impDF(self):
        return pd.read_csv(myDataFramePath)

    def LastEntry(self):

If I use ImportedDF().impDF(), Python will read the DataFrame correctly, but I am troubled because of several different behaviours I was expecting and errors I am facing with this class:

  1. I expected my class to behaviour as if by simply calling ImportedDF() I would get the DataFrame, since the .impDF() method is declared on its __init__ method; this also does not work upon defining it as ImportedDF(pandas.core.frame.DataFrame) so it inherits the methods of a regular pandas DataFrame.

  2. Why is it that ImportedDF().impDF() works, but ImportedDF.impDF() outputs a TypeError: impDF() missing 1 required positional argument: 'self'? Isn't there a way to define my class ImportedDF so I don't have to call it with parenthesis every time (thus only typing them on ImportedDF's methods)?

  3. I created a custom method .LastEntry() so it prints the last row of this imported DataFrame, but ImportedDF().LastEntry() returns an AttributeError: 'ImportedDF' object has no attribute 'iloc' and ImportedDF.LastEntry() (preferred) also returns a TypeError as described in 2, how to make this work?

I know the solution is tied to the definition or not of a parent class as a pandas DataFrame and/or how I instatiate it with __init__, but I haven't been able to find a solution for some time now.

I could, of course, define .impDF() as a function and not a class method, but that would make me unable to leverage it with a single solution that also allows me to use .LastEntry()

0 Answers