Replace the values ​​in the list depending on the value of another list?

I have two lists of the same length. One represents actual values, the other represents some qualities. Depending on the quality threshold (4), I want to replace the values ​​with some other value (p. 17). My approach was to iterate over the qualities with enumerateto get the index and replace that specific index in the values.

Is there a better way to do this?

import numpy as np

values = np.array([4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
quality = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

threshold = 4
value = 17

for i, qual in enumerate(quality):
    if qual < threshold:
        values[i] = value

# [17 17 17 17  4  4  4  4  4  4]
print(values) 
+4
source share
1 answer

You can work with arrays of masks and boolean indexing in :

values[quality < threshold] = value

should do the trick without iteration:

import numpy as np

values = np.array([4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
quality = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

threshold = 4
value = 17

values[quality < threshold] = value

print(values)  # array([17, 17, 17, 17,  4,  4,  4,  4,  4,  4])
+3
source

Source: https://habr.com/ru/post/1664900/


All Articles