python - Replacing minimum element in a numpy array subject to a condition -


i need replace element of numpy array subject minimum of numpy array verifying 1 condition. see 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 expecting label now

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

instead getting

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

this consequence of known fact numpy arrays not updated double slicing.

anyway, can't figure out how rewrite above code in simple way. hint?

you triggering numpy's advanced indexing chaining of indexing, assigning doesn't go through. solve this, 1 way store indices corresponding mask , use indexing. here's 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]) 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -