我正在嘗試創建一個非常簡單的模型來檢查給定一周與前一周的能源價格比較。所以我在整個熊貓資料框中應用了一個函式。我正在努力解決的是在列中獲取較早的值。我已將索引轉移到另一列(稱為計數器),所以我可以用它減去偏移量。我可以使用它來獲得所需的位置,但我不能從該 int 轉到列中的值。我知道第一個值會產生錯誤(加上原始資料中的一些缺失值),所以我正在使用 try/except 并且我已經收集了額外的資料,因此在開始時獲取一些 NaN 不是問題。
def u(df):
if df['Weekday'] in {0,1,4,5,6}: # For Mon, Tue, Thur, Fri, Sat & Sun one week shift
offset=168
else:
offset=24
position=df['Counter']-offset
try:
oldprice=df.iat[position,'Price'] #Never works, always leads to exception
except:
oldprice = np.nan
try:
olddemand =df.iat[position,'Demand']
except:
olddemand = np.nan
print(oldprice)
newdemand = df['Demand']
currentprice =df['Price']
expprice=oldprice*(olddemand/newdemand)
u=currentprice-expprice
return u
results=df2.apply(u,axis=1)
問題是嘗試永遠不會奏效,我得到了全面的 NaN(我也嘗試將例外設定為 1000 并且我得到了很高的值)。柜臺似乎作業正常。我早些時候列印了它,它的行為符合預期并且是一個 int。我也嘗試過 .at 但沒有成功。感謝您的時間。
uj5u.com熱心網友回復:
目前,axis=1您的函式u()使用的引數不是整個 DataFrame,而是單行,因此您無法訪問其他行。一種解決方案是將整個 DataFrame 作為引數傳遞。您的功能u()將變為:
def u(row, df):
if row['Weekday'] in {0, 1, 4, 5, 6}: # For Mon, Tue, Thur, Fri, Sat & Sun one week shift
offset = 168
else:
offset = 24
position = row['Counter'] - offset
try:
oldprice = df.loc[position]['Price']
except:
oldprice = np.nan
try:
olddemand = df.loc[position]['Demand']
except:
olddemand = np.nan
print(oldprice)
newdemand = row['Demand']
currentprice = row['Price']
expprice = oldprice * (olddemand / newdemand)
u = currentprice - expprice
return u
為了傳遞資料框,您需要添加 arg :
results = df2.apply(u, args=(df2,), axis=1)
請注意,如果沒有您的資料樣本,我無法確定輸出是否正確。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444002.html
上一篇:對熊貓資料框進行對角化
