我在我的類中有不同的方法,它們使用同一個pandas資料框架。我是否有辦法將資料框架作為引數傳遞給每個方法,而不是將資料框架宣告為一個類變數,以便所有方法可以共享它。
我嘗試了這里給出的解決方案,但無法使其發揮作用。將 pandas 資料框架作為靜態類變數分配給一個物件--記憶體的使用(Python)
一個例子,我曾嘗試過將資料框架作為類變數來使用,但未能成功。
我想做的一個例子是
我想做的一個例子是
import pandas as pd
df_temp = pd.DataFrame()
df_temp = some_df.copy() #假設我正在復制some_df到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)
我作為引數傳遞的dataframe(df_temp)在兩種情況下都是一樣的,有什么好的方法可以消除傳遞它的必要性?
uj5u.com熱心網友回復:
你可以在構造物件時傳遞你的資料框架,并將其分配到一個實體變數中,就像這樣:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/328119.html
標籤:
下一篇:將資料從A類中的物件傳遞給B類
