How to set cell values โ€‹โ€‹in `np.array ()` based on a condition?

I have a numpy array and a list of valid values โ€‹โ€‹in this 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 good pythonic way to set all array values โ€‹โ€‹to zero that are not on the list of valid values, but 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], ... ] 

Next, a copy of the array is created in memory, which is bad for large arrays :

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

It seems to me that at the moment I loop over each element of the array and set it to zero if it is in the valid list.

Edit: I found the answer, suggesting that there was no function in place in place. Also stop changing my spaces. Itโ€™s easier to see changes in arr using them.

+5
source share
2 answers

You can use np.place to update in-situ -

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

Run Example -

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

At the same time, you can use np.put -

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

Run Example -

 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]]) 
+3
source

Indexing with booleans will also work:

 >>> arr = np.array([[1, 2, 0], [2, 2, 0], [4, 1, 0], [4, 1, 0], [3, 2, 0]]) >>> arr[~np.in1d(arr, valid).reshape(arr.shape)] = 0 >>> arr array([[1, 0, 0], [0, 0, 0], [4, 1, 0], [4, 1, 0], [0, 0, 0]]) 
+1
source

Source: https://habr.com/ru/post/1240251/


All Articles