我有一个pandas Dataframe,如下所示
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'])
却给了我一个错误。任何帮助都会很感激。而且,任何其他的优化技术在这个问题上也会很好!
您不需要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
将函数更改为
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