假設我有一個資料框(df_1),其“高”列限制以百分位數定義,如下所示:
df_1:
A B C
72 57 61
3 52 32
64 51 93
71 79 91
25 23 31
91 90 1
43 44 84
98 91 8
11 49 38
65 33 59
# High Percentiles defined for each column as a variable
A_High = np.percentile(df_1['A'], 60)
B_High = np.percentile(df_1['B'], 60)
C_High = np.percentile(df_1['C'], 60)
#The output for the above variables:
# A_High = 67.39999999999999
# B_High = 54.0
# C_High =59.8
我正在嘗試創建一個函式,該函式使用上面的百分位變數和具有多個條件的 IF 陳述句來過濾資料幀的結果。然后,過濾后的結果在名為 Alerts 的單獨列中編譯為 1 或 0。我已經能夠使用以下代碼成功執行此操作:
def Alert(df):
if df['A'] >= 67.39999999999999 and df['B'] >= 54.0 and df['C'] >= 59.8:
return 1
else:
return 0
df_1.insert(3, 'Alert', df_1.apply(Alert, axis=1))
OUTPUT:
A B C Alert
72 57 61 1
3 52 32 0
64 51 93 0
71 79 91 1
25 23 31 0
91 90 1 0
43 44 84 0
98 91 8 0
11 49 38 0
65 33 59 0
但是當我在函式本身中定義百分位數時,它不會生成所需的輸出。
def Alert(df):
A_High = np.percentile(df['A'], 60)
B_High = np.percentile(df['B'], 60)
C_High = np.percentile(df['C'], 60)
if df['A'] >= A_High and df['B'] >= B_High and df['C'] >= C_High:
return 1
else:
return 0
df_1.insert(3, 'Alert', df_1.apply(Alert, axis=1))
OUTPUT:
A B C Alert
72 57 61 1
3 52 32 1
64 51 93 1
71 79 91 1
25 23 31 1
91 90 1 1
43 44 84 1
98 91 8 1
11 49 38 1
65 33 59 1
我想在不同的資料幀上運行這個函式,并且不想每次都手動輸入上限值。如果有人可以在這里幫助我,將不勝感激(僅供參考:Python新手)
uj5u.com熱心網友回復:
Pandas 應用函式迭代資料幀的行,因此 A_High B_High 和 C_High 的計算值將在每次迭代時發生變化,您可以創建不同的函式來回傳這些值并將值傳遞給 Alert 函式
例子:
def percentiles(df):
A_High = np.percentile(df['A'], 60)
B_High = np.percentile(df['B'], 60)
C_High = np.percentile(df['C'], 60)
return A_High,B_High,C_High
def Alert(df,A_High,B_High,C_High):
if df['A'] >= A_High and df['B'] >= B_High and df['C'] >= C_High:
return 1
else:
return 0
A_High,B_High,C_High=percentiles(df_1)
df_1.insert(3, 'Alert', df_1.apply(Alert, axis=1,args=A_High,B_High,C_High))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506833.html
上一篇:無法將字串作為函式輸入
下一篇:在python中計算業務作業時間