Mini Fridge
Mini Fridge

Reputation: 939

Generate sparse vector

I have two lists. One with indexes (set obviously) and one with values. Is it possible to convert them in a numpy array with fixed size efficiently?

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

What I want to output is:

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

Upvotes: 0

Views: 430

Answers (1)

Ogaday
Ogaday

Reputation: 684

It's easy in two lines, if you want:

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. ])

Upvotes: 3

Related Questions