user308827
user308827

Reputation: 21981

Pass pandas dataframe into class

I would like to create a class from a pandas dataframe that is created from csv. Is the best way to do it, by using a @staticmethod? so that I do not have to read in dataframe separately for each object

Upvotes: 11

Views: 49886

Answers (2)

Tom
Tom

Reputation: 1063

I would think you could create the dataframe in the first instance with

a = MyClass(my_dataframe)

and then just make a copy

b = a.copy(deep=True)

Then b is independent of a

Upvotes: 4

Simeon Visser
Simeon Visser

Reputation: 122376

You don't need a @staticmethod for this. You can pass the pandas DataFrame whenever you're creating instances of the class:

class MyClass:

    def __init__(self, my_dataframe):
        self.my_dataframe = my_dataframe

a = MyClass(my_dataframe)
b = MyClass(my_dataframe)

At this point, both a and b have access to the DataFrame that you've passed and you don't have to read the DataFrame each time. You can read the data from the CSV file once, create the DataFrame and construct as many instances of your class as you like (which all have access to the DataFrame).

Upvotes: 19

Related Questions