如何应用 Numpy Vectorize 而不是应用函数

how to apply Numpy Vectorize instead of apply function

我有一个 pandas 数据框如下

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 array

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