Python 按索引填充numpy数组
我有一个函数,它给我给定值的索引。例如Python 按索引填充numpy数组,python,arrays,numpy,Python,Arrays,Numpy,我有一个函数,它给我给定值的索引。例如 def F(value): index = do_something(value) return index 我想用这个索引将一个巨大的numpy数组填充1s。让我们调用数组功能 l = [1,4,2,3,7,5,3,6,.....] 注:features.shape[0]=len(l) 是否有一种类似python的方法来执行此操作(因为如果数组很大,循环会花费很多时间)?如果可以将F(value)矢量化,则可以编写如下代码 indices
def F(value):
index = do_something(value)
return index
我想用这个索引将一个巨大的numpy数组填充1s。让我们调用数组功能
l = [1,4,2,3,7,5,3,6,.....]
注:features.shape[0]=len(l)
是否有一种类似python的方法来执行此操作(因为如果数组很大,循环会花费很多时间)?如果可以将
F(value)
矢量化,则可以编写如下代码
indices = np.arange(features.shape[0])
feature_indices = F(l)
features.flat[indices, feature_indices] = 1
试试这个:
i = np.arange(features.shape[0]) # rows
j = np.vectorize(F)(np.array(l)) # columns
features[i,j] = 1
F(值)未矢量化
i = np.arange(features.shape[0]) # rows
j = np.vectorize(F)(np.array(l)) # columns
features[i,j] = 1