Stumpp Stumpp - 3 months ago 13
Python Question

Change all values exceeding threshold to the negative of itself

I have an array with a bunch of rows and three columns. I have this code below which changes every value exceeding the threshold, to 0. Is there a trick to make the replace value to the negative of which number exceeds the threshold? Lets say i have an array

np.array([[1,2,3],[4,5,6],[7,8,9]])
. I choose column one and get an array with the values 1,4,7(first values of each row) If the threshold is 5, is there a way to make every value larger than 5 to the negative of it self, so that 1,4,7 changes to 1,4,-7?

import numpy as np

arr = np.ndarray(my_array)
threshold = 5
column_id = 0
replace_value = 0
arr[arr[:, column_id] > threshold, column_id] = replace_value

Answer

Try this

In [37]: arr = np.array([[1,2,3],[4,5,6],[7,8,9]])

In [38]: arr[:, column_id] *= (arr[:, column_id] > threshold) * -2 + 1

In [39]: arr
Out[39]:
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [-7,  8,  9]])