python - 如何将熊猫数据框分配给类变量?
问题描述
我的班级有不同的方法,它们使用相同的熊猫数据框。不是将相同的数据框作为参数传递给每个方法,有没有一种方法可以将数据框声明为类变量,以便所有方法都可以共享它。
我尝试了这里给出的解决方案,但无法使其工作。将 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)对于这两种情况都是相同的,消除传递它的需要的最佳方法是什么?
解决方案
您可以在构造对象时传递数据框并将其分配给如下实例变量:
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)
推荐阅读
- laravel - Laravel nova - 按删除按钮不出现确认模式
- python - ImportError: 无法从 'robot.libdocpkg.htmlwriter' 导入名称 'DocToHtml' (C:\Python37\lib\site-packages\robot\libdocpkg\htmlwriter.py)
- wso2 - WSO2 IS 5.11 - 无法在 Apple 设备上使用 FIDO 身份验证
- java - 如何从对象访问元素?爪哇
- apache-kafka - Kafka - 无法建立与节点 -1 (localhost/127.0.0.1:2181) 的连接。经纪人可能不可用
- python - 使用 Beautiful Soup 在 Youtube 频道上抓取视频
- visual-studio-code - 无法在 Python 交互窗口中显示变量列
- python - 为每个具体用户的消息保存一些信息
- github - 我们可以在 GitHub Action 工作流程中将运行次数分组到一个名称下吗?
- tensorflow - Google Colab 和 GPU 中的教程出错:“无法获得卷积算法”