Stumpp
Stumpp

Reputation: 289

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

Upvotes: 0

Views: 107

Answers (2)

jinhwanlazy
jinhwanlazy

Reputation: 3571

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]])

Sorry for editing later. I recommend below, which may be faster.

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 > threshold] *= -1

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

Upvotes: 2

SUNITHA K
SUNITHA K

Reputation: 148

    import numpy as np
    x= list(np.arange(1,10))
    b = []
    for i in x:
        if i > 4:
            b.append(-i)
        else:
            b.append(i)

    print(b)
    e = np.array(b).reshape(3,3)
    print('changed array')
    print(e[:,0])

    output :
    [1, 2, 3, 4, -5, -6, -7, -8, -9]
    changed array  :
   [ 1  4 -7]

Upvotes: 0

Related Questions