[SOLVED] Assign value to subset of numpy array

Issue

Given the following array:

x = np.zeros((1, 5))
x
# array([[0., 0., 0., 0., 0.]])

I’d like to be able to create array([[0., 3., 1., 0., 8.]]) using something like:

values = [3, 1, 8]
indices = [1, 2, 4]
x.iloc[indices] = values

I understand that this doesn’t work – but I’m not sure what an idiomatic approach to this sort of thing in numpy would be.

The following works, but it doesn’t seem like it’s a sensible approach using numpy:

values = [3, 1, 8]
indices = [1, 2, 4]
for i, v in zip(indices, values):
    row[i] = v

Solution

Just move the indexer to the second position (because you’re modifying values in the second dimension):

x[:, indices] = values

Output:

>>> x
array([[0., 3., 1., 0., 8.]])

Answered By – richardec

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *