通过索引填充numpy数组

2 投票
2 回答
3958 浏览
提问于 2025-04-18 01:00

我有一个函数,可以根据给定的值返回它在列表中的位置,比如:

def F(value):
   index = do_something(value)
   return index

我想用这个位置来填充一个很大的numpy数组,里面全是1。我们把这个数组叫做 features

l = [1,4,2,3,7,5,3,6,.....]

注意:features.shape[0] = len(l)

for i in range(features.shape[0]):
    idx = F(l[i])
    features[i, idx] = 1

有没有什么更简洁的方法来实现这个(因为如果数组很大,使用循环会花很多时间)?

2 个回答

1

试试这个:

i = np.arange(features.shape[0]) # rows
j = np.vectorize(F)(np.array(l)) # columns
features[i,j] = 1
2

如果你能把 F(value) 变成向量化的形式,你可以写出类似下面的代码:

indices = np.arange(features.shape[0])
feature_indices = F(l)

features.flat[indices, feature_indices] = 1

撰写回答