首页 > 解决方案 > 如何将熊猫数据框分配给类变量?

问题描述

我的班级有不同的方法,它们使用相同的熊猫数据框。不是将相同的数据框作为参数传递给每个方法,有没有一种方法可以将数据框声明为类变量,以便所有方法都可以共享它。

我尝试了这里给出的解决方案,但无法使其工作。将 pandas 数据框作为静态类变量分配给对象 - 内存使用(Python)

我正在尝试做的一个例子是

import pandas as pd
df_temp = pd.DataFrame()
df_temp = some_df.copy()     #Assume that I am copying some_df to df_temp

class Weather:
  # I tried using the below and not pass the dataframe to my methods but it didnt work.
  # df = df_temp
  def __init__(self, baseyear):
    self.baseyear = baseyear
   
  def HU_monthly(self, df, month):
    df_HU = df.groupby(['Station','Year','Month'])['Heat Units'].sum().round(2).reset_index()
    return(df_HU)
  
  def HU_range(self, df, first_month, last_month):
    df_between_months = df[(first_month <=df['Month'])&(df['Month']<=last_month)]
    return(df_between_months)

monthly = Weather(2000)
df_1 = monthly.HU_monthly(df_temp, 8)

ranger = Weather(2010)
df_2 = ranger.HU_range(df_temp, 5, 10)

我作为参数传递的数据帧(df_temp)对于这两种情况都是相同的,消除传递它的需要的最佳方法是什么?

标签: pythonpandasdataframeclass

解决方案


您可以在构造对象时传递数据框并将其分配给如下实例变量:

class Weather:
    def __init__(self, df):
        self.df = df

然后您可以像这样在所有方法中访问数据框:

def HU_monthly(self, month):
    df_HU = self.df.groupby(['Station','Year','Month'])['Heat Units'].sum().round(2).reset_index()
    return(df_HU)

创建您的类对象,如下所示:

weather = Weather(df)

推荐阅读