You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将pandas DataFrame赋值为类变量实现多方法共用?

免传参实现方案说明

问题原因

你之前尝试类变量方案未生效,是因为仅声明了类变量,但方法仍保留了df形参,方法内实际调用的是传入的参数而非类内存储的df,调整方法引用逻辑即可。

方案1:类变量共享(适合所有实例共用同一个df的场景)

所有实例共享同一份df引用,无额外内存开销,pandas DataFrame作为类变量存储时仅保留引用,不会触发全量拷贝:

import pandas as pd
df_temp = some_df.copy()     # 假设此处将some_df拷贝到df_temp

class Weather:
  # 声明类变量,所有实例共享
  df = df_temp
  def __init__(self, baseyear):
    self.baseyear = baseyear
   
  def HU_monthly(self, month):
    df_HU = Weather.df.groupby(['Station','Year','Month'])['Heat Units'].sum().round(2).reset_index()
    return df_HU
  
  def HU_range(self, first_month, last_month):
    df_between_months = Weather.df[(first_month <= Weather.df['Month'])&(Weather.df['Month']<=last_month)]
    return df_between_months

# 调用时无需传入df
monthly = Weather(2000)
df_1 = monthly.HU_monthly(8)

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

方案2:实例存储(更灵活,支持不同实例用不同df)

将df作为初始化参数,设置默认值为全局df,既可以满足默认场景免传参的需求,也支持自定义传入其他df:

import pandas as pd
df_temp = some_df.copy()

class Weather:
  def __init__(self, baseyear, df=df_temp):
    self.baseyear = baseyear
    # 实例维度存储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
  
  def HU_range(self, first_month, last_month):
    df_between_months = self.df[(first_month <= self.df['Month'])&(self.df['Month']<=last_month)]
    return df_between_months

# 默认调用无需传df
monthly = Weather(2000)
df_1 = monthly.HU_monthly(8)

# 需要使用其他df时单独指定即可
custom_weather = Weather(2020, df=other_df)
df_custom = custom_weather.HU_monthly(7)

方案选择建议

  • 全场景共用同一份df:选方案1,内存占用最低
  • 存在不同实例用不同df的可能:选方案2,扩展性更强

内容的提问来源于stack exchange,提问作者Neeraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:15:01