2

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
2
  • Beside the point, but row is not defined. Looks like it's supposed to be row = x[0]. Commented Mar 22, 2022 at 21:32
  • Is y = x.iloc[indices] = values a typo? Commented Mar 22, 2022 at 21:32

2 Answers 2

4

You can use the put method from numpy to achieve this:

np.put(x, indices, values)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.