Home > database >  finding special elements in an array
finding special elements in an array

Time:06-25

I have such an array:

    x = np.array([[1,2], [3,4], [5,6]]) 

I want to find elements bigger than 3. I am trying:

     ppoc = np.zeros((3,3))

     ixu = np.argwhere(x > 2)
     ppoc = ppoc[0, ixu]

But the problem is ppoc is a 2*2 array, but I need to return an array with the same size as x, which the rest of the elements are zero.

ppoc must look like:

ppoc = [[0,0], [3,4], [5,6]]

Does anyone have an idea how to do that?

CodePudding user response:

You can vectorize the computation that sends t to 0 or t depending on if t < 3, then apply this vectorized function to x:

np.vectorize(lambda t: 0 if t < 3 else t)(x)

this evaluates to:

array([[0, 0],
       [3, 4],
       [5, 6]])

CodePudding user response:

If i understood correctly, you want to replace every element in the array by 0 if it's smaller than 3. Here's the answer :

x = np.array([[1,2], [3,4], [5,6]])
ppoc = x * (x > 2)

Output :
array([[0, 0],
   [3, 4],
   [5, 6]])

Is this what you wanted ?

  • Related