Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 674
user308827 Avatar asked Nov 15 '14 19:11

user308827


People also ask

How do we pass in DataFrame in pandas?

In most cases, you'll use the DataFrame constructor and provide the data, labels, and other information. You can pass the data as a two-dimensional list, tuple, or NumPy array. You can also pass it as a dictionary or Pandas Series instance, or as one of several other data types not covered in this tutorial.

Can we pass DataFrame to a function?

Arbitrary functions can be applied along the axes of a DataFrame or Panel using the apply() method, which, like the descriptive statistics methods, takes an optional axis argument. By default, the operation performs column wise, taking each column as an array-like.

Is a pandas DataFrame a class?

Overview: The Python Data Analysis library pandas, provides the DataFrame class as a container for storing and manipulating two-dimensional data. In a nutshell a pandas DataFrame is a two-dimensional array with versatile computing capabilities. The DataFrame class encapsulates a two-dimensional array – a numpy.

How do you convert a DataFrame to a list of objects?

The command to convert Dataframe to list is pd. DataFrame. values. tolist().


2 Answers

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).

like image 118
Simeon Visser Avatar answered Sep 20 '22 16:09

Simeon Visser


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()

Then b is independent of a

like image 39
Tom Avatar answered Sep 20 '22 16:09

Tom