我有一個熊貓資料框如下
data = {
'ID' : [0,0,0,0,0,1],
'DAYS': [293,1111,3020,390,210,10],
}
df = pd.DataFrame(data, columns = ['ID','DAYS'])
ID DAYS
0 0 293
1 0 1111
2 0 3020
3 0 390
4 0 210
5 1 10
我想要做的是具有以下條件的簡單應用函式,并將列輸出為布林值:
df['bool'] = df.apply(lambda x:( x['DAYS'] < 365),axis =1 )
我想優化這個 apply-lambda 部分。我設法在 numpy 陣列中做
df['bool_numpy'] = np.where(df['DAYS'] <365 ,True ,False)
但我正在努力為 np.vectorize 方法應用同樣的東西。
def copy_filter(df):
if df['DAYS'] <365:
return True
else:
return False
a= np.vectorize(copy_filter, otypes = [bool])
df['bool_vectorize'] = a(df['DAYS'])
但給了我一個錯誤。任何幫助,將不勝感激。而且,關于這個問題的任何其他優化技術也會很棒!
uj5u.com熱心網友回復:
你并不需要apply,也不vectorize為此:
df['bool'] = df['DAYS'] < 365
輸出:
ID DAYS bool
0 0 293 True
1 0 1111 False
2 0 3020 False
3 0 390 False
4 0 210 True
5 1 10 True
uj5u.com熱心網友回復:
將您的功能更改為
def copy_filter(x):
if x <365:
return True
else:
return False
a= np.vectorize(copy_filter, otypes = [bool])
df['bool_vectorize'] = a(df['DAYS'])
df
ID DAYS bool_vectorize
0 0 293 True
1 0 1111 False
2 0 3020 False
3 0 390 False
4 0 210 True
5 1 10 True
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325917.html
