2

I need to replace an element of a numpy array subject to the minimum of another numpy array verifying one condition. See the following minimal example:

arr = np.array([0, 1, 2, 3, 4])
label = np.array([0, 0, 1, 1, 2])
cond = (label == 1)
label[cond][np.argmin(arr[cond])] = 3

I would be expecting that label is now

 array([0,  0,  3,  1, 2])

instead I am getting

 array([0,  0,  1,  1, 2])

This is a consequence of the known fact that numpy arrays are not updated with double slicing.

Anyway, I can't figure out how to rewrite the above code in a simple way. Any hint?

0

1 Answer 1

2

You are triggering NumPy's advanced indexing with that chaining of indexing, so the assigning doesn't go through. To solve this, one way would be to store the indices corresponding to the mask and then use indexing. Here's the implementation -

idx = np.where(cond)[0]
label[idx[arr[idx].argmin()]] = 3

Sample run -

In [51]: arr = np.array([5, 4, 5, 8, 9])
    ...: label = np.array([0, 0, 1, 1, 2])
    ...: cond = (label == 1)
    ...: 

In [52]: idx = np.where(cond)[0]
    ...: label[idx[arr[idx].argmin()]] = 3
    ...: 

In [53]: idx
Out[53]: array([2, 3])

In [54]: label
Out[54]: array([0, 0, 3, 1, 2])
Sign up to request clarification or add additional context in comments.

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.