Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Received all indexes of elements greater than x in ndarray of size n*n python

I have a ndarray of size n*n (200,200).

I want to find all the indexes of the values that greater then 0 and then change them to 1.

I try to do something like that and I received exception.

toggleOn_index = [x for x in  net if x>0]
net[toggleOn_index]=1

What is the most efficient way to do that?

like image 987
MAK Avatar asked Nov 01 '25 01:11

MAK


1 Answers

If I start with some array a as follows

>>> a = np.random.rand(5, 5) - 0.5
>>> a
array([[ 0.24116601, -0.23917393,  0.46607471,  0.08560729,  0.33878893],
       [ 0.24681769, -0.01693847,  0.22579766, -0.38570793, -0.2075437 ],
       [-0.19602781, -0.46108244, -0.40341244,  0.42579818,  0.4655471 ],
       [-0.14669409,  0.36171014, -0.36496558, -0.30983999, -0.06633584],
       [-0.09159042,  0.23346471,  0.37680536, -0.09281205, -0.04552193]])

I can assign to all the elements that are greater than 0 using

>>> a[a > 0] = 1
>>> a
array([[ 1.        , -0.23917393,  1.        ,  1.        ,  1.        ],
       [ 1.        , -0.01693847,  1.        , -0.38570793, -0.2075437 ],
       [-0.19602781, -0.46108244, -0.40341244,  1.        ,  1.        ],
       [-0.14669409,  1.        , -0.36496558, -0.30983999, -0.06633584],
       [-0.09159042,  1.        ,  1.        , -0.09281205, -0.04552193]])
like image 168
Cory Kramer Avatar answered Nov 03 '25 17:11

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!