andrea m.
andrea m.

Reputation: 688

Replace values of an array based on a vector of indices

I have an array of values and an array of indices. I would like to use indices to generate an array of the same size with values corresponding to the index of the first array:

vals = np.array([.2,.3])
ind = np.array([0,0,1,0])

expected outcome:

np.array([.2,.2,.3,.2])

Upvotes: 0

Views: 521

Answers (2)

bnlucas
bnlucas

Reputation: 1764

Not sure if this is the NumPy best practice way, but you can do:

[vals[i] for i in ind]
new_vals = np.array([vals[i] for i in ind])

Upvotes: 0

Paddy Harrison
Paddy Harrison

Reputation: 2002

You can just index your value array with the indices array as they are integers (required for indexing):

vals[ind]

which produces:

array([0.2, 0.2, 0.3, 0.2])

as desired.

Upvotes: 1

Related Questions