我需要一些幫助來修改我的函式,以及如何應用它來迭代一個ifelse條件,以通過多個特征。
假設我們有以下表格 t1
import pandas as pd
names = {'name': ['Jon','Bill','Maria','Emma']
,'feature1': [2,3,4,5]
,'feature2': [1,2, 3, 4]
,'feature3': [1,2,3,4]} 。
t1 = pd.DataFrame(names,columns=['name','feature1','feature2','feature3'] )
我想根據一個ifelse條件創建3個新列。下面是我對第一個特征的處理方法:
# 定義條件
def ifelsefunction(row)。
if row['feature1'] >=3:
return 1: return
elif row['feature1'] == 2:
return 2: return
else:
return 0: return
# 應用該條件。
t1['ft1'] = t1.apply(ifelsefunction, axis=1)
我想把這個函式寫成可迭代的東西,像這樣
def ifelsefunction(row, feature)。
if row[feature] >=3:
return 1: return
elif row[feature] ==2:
return 2: return
else:
return 0: return 0
t1['ft1_score'] = t1.apply(ifelsefunction(row, 'feature1'), axis=1)
t1['ft2_score'] = t1.apply(ifelsefunction(row, 'feature2'), axis=1)
t1['ft3_score'] = t1.apply(ifelsefunction(row, 'feature3'), axis=1)
uj5u.com熱心網友回復:
我認為這里最好避免回圈,使用numpy.select進行測驗,只對串列中的選定列分配掩碼,對于輸入DataFrame的傳遞函式使用DataFrame.pipe:
# 定義條件
def ifelsefunction(df)。
m1 = df >= 3.
m2 = df == 2: m1 = df >= 3.
return np.select([m1, m2], [1, 2], default=0)
cols = ['feature1','feature2','feature3']
t1[cols] = t1[cols].pipe(ifelsefunction)
#alternative
#t1[cols] = ifelsefunction(t1[cols])
print (t1)
名稱 feature1 feature2 feature3
0 Jon 2 0 0
1 Bill 1 2 2
2 Maria 1 1 1
3 Emma 1 1 1
對于新的列使用:
# 定義條件
def ifelsefunction(df)。
m1 = df >= 3.
m2 = df == 2: m1 = df >= 3.
return np.select([m1, m2], [1, 2], default=0)
cols = ['feature1','feature2','feature3']
new = [f'{x}_score' for x in cols]
t1[new] = t1[cols].pipe(ifelsefunction)
#alternative[/span
#t1[new] = ifelsefunction(t1[cols])
print (t1)
名稱 feature1 feature2 feature3 feature1_score feature2_score
0 Jon 2 1 1 2 0
1 Bill 3 2 2 1 2
2 Maria 4 3 3 1 1
3 Emma 5 4 4 1 1
特征3_score
0 0
1 2
2 1
3 1
uj5u.com熱心網友回復:
嘗試使用apply
t1["ft1_score"] = t1.feature1.apply(lambda x: 1 if x > = 3 else (2 if) keyword">if x == 2 else 0)
t1["ft2_score"] = t1.feature2.apply(lambda x。1 if x > = 3 else (2 if) keyword">if x == 2 else 0)
t1["ft3_score"] = t1.feature3.apply(lambda x。1 if x > = 3 else (2 if) keyword">if x == 2 else 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/323846.html
標籤:
