Setting null values ​​in a numpy array

How can I specify some values ​​in a numpy array based on a condition? I don’t understand why I end with 0 instead of zero or empty values, where the condition is not met ... b is a numpy array filled with 0 and 1 values, c is another completely filled numpy array. All arrays 71x71x166

a = np.empty(((71,71,166))) d = np.empty(((71,71,166))) for indexes, value in np.ndenumerate(b): i,j,k = indexes a[i,j,k] = np.where(b[i,j,k] == 1, c[i,j,k], d[i,j,k]) 

I want to end an array that only has values ​​in which the condition is satisfied, and is empty everywhere, but without changing its shape.

FULL EDITION FOR DEVELOPMENT, as requested:
I start with a float-filled array with the form (71,71,166)
I am creating an int array based on the trim applied to the floating point array, basically creating several bins, roughly allocating 10 areas inside the array with 0 values ​​between
I want to end up with an array with a shape (71,71,166), which has average values ​​in a certain direction of the array (assuming the vertical direction, if you think of a three-dimensional array as a 3D cube) of a certain "bin", .. .
so I tried to skip the “bunkers” b == 1, b == 2, etc., sampling the float where this condition is met, but zero in another place, so I can take the average value and then recombine into one array in end of loop ...
Not sure what I understood myself. I use np.where and use indexing as I keep getting errors when I try to do this, although this seems very inefficient.

+5
source share
2 answers

Consider the following example:

 import numpy as np data = np.random.random((4,3)) mask = np.random.random_integers(0,1,(4,3)) data[mask==0] = np.NaN 

The data will be set to nan wherever mask is 0. You can use any condition that you want, of course, or do something else for different values ​​in b.

To erase everything except a specific bean, try the following:

 c[b!=1] = np.NaN 

So, to make a copy of everything in a specific bunker:

 a = np.copy(c) a[b!=1] == np.NaN 

Get the average of everything in the basket:

 np.mean(c[b==1]) 

So perhaps this can do what you want (where bit is a list of bin values):

 a = np.empty(c.shape) a[b==0] = np.NaN for bin in bins: a[b==bin] = np.mean(c[b==bin]) 
+4
source

np.empty sometimes fills array 0; it is undefined what the contents of the empty() array are, so 0 is excellent. For example, try this instead:

 d = np.nan * np.empty((71, 71, 166)). 

But consider using the power of numpy and do not iterate over the array:

 a = np.where(b, c, d) 

(since b is 0 or 1, I ruled out an explicit comparison of b == 1 )

You might want to consider a masked array instead:

 a = np.ma.masked_where(b, c) 

which apparently makes more sense regarding your question: “how can I nullify certain values ​​in a numpy array based on a condition” (replace null with a mask, and you're done).

+1
source

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


All Articles