生成稀疏向量

时间:2015-12-11 14:53:54

标签: python numpy scipy

我有两个清单。一个带索引(显然设置),一个带值。是否可以有效地将它们转换为具有固定大小的numpy数组?

indexes = [1,2,6,7] 
values = [0.2,0.5,0.6,0.2]
size = 10

我想输出的是:

print(magic_func(indexes,values,size))
array(0,0.2,0.5,0,0,
      0,0.6,0.2,0,0)

1 个答案:

答案 0 :(得分:3)

如果你愿意,可以分两行:

In [1]: import numpy as np

In [2]: arr = np.zeros(size)

In [3]: arr[indexes] = values

In [4]: arr
Out[4]: array([ 0. ,  0.2,  0.5,  0. ,  0. ,  0. ,  0.6,  0.2,  0. ,  0. ])