将pandas数据框传递给类 [英] Pass pandas dataframe into class
问题描述
我想从从csv创建的pandas数据框中创建一个类.使用@staticmethod是最好的方法吗?这样我就不必为每个对象分别读取数据框
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
推荐答案
您不需要@staticmethod
.每当您创建类的实例时,都可以传递pandas DataFrame:
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)
这时,a
和b
都可以访问您传递的数据框,而不必每次都读取该数据框.您可以一次从CSV文件中读取数据,创建DataFrame并根据需要构造任意数量的类实例(所有这些实例都可以访问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).
这篇关于将pandas数据框传递给类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!