Change all values exceeding threshold to the negative of itself
<p>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 <code>np.array([[1,2,3],[4,5,6],[7,8,9]])</code>. 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?</p>

<pre><code>import numpy as np

arr = np.ndarray(my_array)
threshold = 5
column_id = 0
replace_value = 0
arr[arr[:, column_id] &gt; threshold, column_id] = replace_value
</code></pre>

<p>Try this</p>

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

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

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

<hr>

<p>Sorry for editing later. I recommend below, which may be faster.</p>

<pre><code>In [48]: arr
Out[48]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [49]: col = arr[:, column_id]

In [50]: col[col &gt; threshold] *= -1

In [51]: arr
Out[51]:
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [-7,  8,  9]])
</code></pre>

python numpy