我的資料框看起來像這樣
frame = pd.DataFrame({'id':[1,2,3,4,5],
'week1_values':[0,0,13,39,64],
'week2_values':[32,35,25,78,200]})
我正在嘗試應用一個函式來計算動態生成名稱的兩列('week1_values'和'week2_values')之間的每周百分比差異。
我想創建一個函式來計算周之間的百分比差異,記住“week1_values”列中的零值。
我的功能是這樣的:
def WoW(df):
if df.iloc[:,1] == 0:
return (df.iloc[:,1] - df.iloc[:,2])
else:
return ((df.iloc[:,1] - df.iloc[:,2]) / df.iloc[:,1]) *100
frame['WoW%'] = frame.apply(WoW,axis=1)
當我嘗試這樣做時,我最終遇到了這個錯誤
IndexingError: ('太多索引器', '發生在索引 0')
應該如何通過列在函式中的位置來指定列?
PS:只是想澄清一下,由于列名是動態生成的,我試圖通過 iloc 函式的位置來選擇它們。
uj5u.com熱心網友回復:
因為使用Series,洗掉索引列:
def WoW(df):
if df.iloc[1] == 0:
return (df.iloc[1] - df.iloc[2])
else:
return ((df.iloc[1] - df.iloc[2]) / df.iloc[1]) *100
frame['WoW%'] = frame.apply(WoW,axis=1)
矢量化替代方案:
s = frame.iloc[:,1] - frame.iloc[:,2]
frame['WoW%1'] = np.where(frame.iloc[:, 1] == 0, s, (s / frame.iloc[:,1]) *100)
print (frame)
id week1_values week2_values WoW% WoW%1
0 1 0 32 -32.000000 -32.000000
1 2 0 35 -35.000000 -35.000000
2 3 13 25 -92.307692 -92.307692
3 4 39 78 -100.000000 -100.000000
4 5 64 200 -212.500000 -212.500000
uj5u.com熱心網友回復:
您可以使用 pandaspct_change方法自動計算百分比變化。
s = (frame.iloc[:, 1:].pct_change(axis=1).iloc[:, -1]*100)
frame['WoW%'] = s.mask(np.isinf(s), frame.iloc[:, -1])
輸出:
id week1_values week2_values WoW
0 1 0 32 32.000000
1 2 0 35 35.000000
2 3 13 25 92.307692
3 4 39 78 100.000000
4 5 64 200 212.500000
但是請注意,您當前在自定義函式中執行此操作的方式是有偏見的。從 0->20,或 10->12,或 100->120 的變化都會產生 20 作為 output,這似乎是模棱兩可的。
建議的替代方案
使用經典的百分比增加,即使它導致無限:
frame['WoW'] = frame.iloc[:, 1:].pct_change(axis=1).iloc[:, -1]*100
輸出:
id week1_values week2_values WoW
0 1 0 32 inf
1 2 0 35 inf
2 3 13 25 92.307692
3 4 39 78 100.000000
4 5 64 200 212.500000
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/421247.html
標籤:
上一篇:如何使用render_template燒瓶將PIL影像顯示為html?
下一篇:具有新列的重復行
