Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set cell values in `np.array()` based on condition?

I have a numpy array and a list of valid values in that array:

import numpy as np
arr = np.array([[1,2,0], [2,2,0], [4,1,0], [4,1,0], [3,2,0], ... ])
valid = [1,4]

Is there a nice pythonic way to set all array values to zero, that are not in the list of valid values and do it in-place? After this operation, the list should look like this:

               [[1,0,0], [0,0,0], [4,1,0], [4,1,0], [0,0,0], ... ]

The following creates a copy of the array in memory, which is bad for large arrays:

arr = np.vectorize(lambda x: x if x in valid else 0)(arr)

It bugs me, that for now I loop over each array element and set it to zero if it is in the valid list.

Edit: I found an answer suggesting there is no in-place function to achieve this. Also stop changing my whitespaces. It's easier to see the changes in arr whith them.

like image 384
con-f-use Avatar asked Sep 25 '22 17:09

con-f-use


1 Answers

You can use np.place for an in-situ update -

np.place(arr,~np.in1d(arr,valid),0)

Sample run -

In [66]: arr
Out[66]: 
array([[1, 2, 0],
       [2, 2, 0],
       [4, 1, 0],
       [4, 1, 0],
       [3, 2, 0]])

In [67]: np.place(arr,~np.in1d(arr,valid),0)

In [68]: arr
Out[68]: 
array([[1, 0, 0],
       [0, 0, 0],
       [4, 1, 0],
       [4, 1, 0],
       [0, 0, 0]])

Along the same lines, np.put could also be used -

np.put(arr,np.where(~np.in1d(arr,valid))[0],0)

Sample run -

In [70]: arr
Out[70]: 
array([[1, 2, 0],
       [2, 2, 0],
       [4, 1, 0],
       [4, 1, 0],
       [3, 2, 0]])

In [71]: np.put(arr,np.where(~np.in1d(arr,valid))[0],0)

In [72]: arr
Out[72]: 
array([[1, 0, 0],
       [0, 0, 0],
       [4, 1, 0],
       [4, 1, 0],
       [0, 0, 0]])
like image 177
Divakar Avatar answered Sep 28 '22 22:09

Divakar