将 Pandas 数据框传递给类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26949755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:40:35  来源:igfitidea点击:

Pass pandas dataframe into class

pythonclasspandas

提问by user308827

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

我想从从 csv 创建的Pandas数据帧创建一个类。使用@staticmethod 是最好的方法吗?这样我就不必为每个对象分别读取数据帧

回答by Simeon Visser

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

你不需要一个@staticmethod。您可以在创建类的实例时传递 pandas DataFrame:

class MyClass:

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

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

At this point, both aand bhave 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).

此时,ab都可以访问您传递的 DataFrame 并且您不必每次都读取 DataFrame。您可以从 CSV 文件中读取一次数据,创建 DataFrame 并根据需要构建任意数量的类实例(它们都可以访问 DataFrame)。

回答by Tom

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

我认为你可以在第一个实例中创建数据框

a = MyClass(my_dataframe)

a = MyClass(my_dataframe)

and then just make a copy

然后复制一份

b = a.copy()

b = a.copy()

Then b is independent of a

那么 b 独立于 a