[Numpy-discussion] Multiple Boolean Operations

Francesc Alted falted@pytables....
Thu May 22 07:04:57 CDT 2008

A Thursday 22 May 2008, Andrea Gavana escrigué:
> Hi All,
>     I am building some 3D grids for visualization starting from a
> much bigger grid. I build these grids by satisfying certain
> conditions on x, y, z coordinates of their cells: up to now I was
> using VTK to perform this operation, but VTK is slow as a turtle, so
> I thought to use numpy to get the cells I am interested in.
> Basically, for every cell I have the coordinates of its center point
> (centroids), named xCent, yCent and zCent. These values are stored in
> numpy arrays (i.e., if I have 10,000 cells, I have 3 vectors xCent,
> yCent and zCent with 10,000 values in them). What I'd like to do is:
> # Filter cells which do not satisfy Z requirements:
> zReq = zMin <= zCent <= zMax
> # After that, filter cells which do not satisfy Y requirements,
> # but apply this filter only on cells who satisfy the above
> condition:
> yReq = yMin <= yCent <= yMax
> # After that, filter cells which do not satisfy X requirements,
> # but apply this filter only on cells who satisfy the 2 above
> conditions:
> xReq = xMin <= xCent <= xMax
> I'd like to end up with a vector of indices which tells me which are
> the cells in the original grid that satisfy all 3 conditions. I know
> that something like this:
> zReq = zMin <= zCent <= zMax
> Can not be done directly in numpy, as the first statement executed
> returns a vector of boolean. Also, if I do something like:
> zReq1 = numpy.nonzero(zCent <= zMax)
> zReq2 = numpy.nonzero(zCent[zReq1] >= zMin)
> I lose the original indices of the grid, as in the second statement
> zCent[zReq1] has no more the size of the original grid but it has
> already been filtered out.
> Is there anything I could try in numpy to get what I am looking for?
> Sorry if the description is not very clear :-D
> Thank you very much for your suggestions.

I don't know if this is what you want, but you can get the boolean 
arrays separately, do the intersection and finally get the interesting 
values (by using fancy indexing) or coordinates (by using .nonzero()).  
Here it is an example:

In [105]: a = numpy.arange(10,20)

In [106]: c1=(a>=13)&(a<=17)

In [107]: c2=(a>=14)&(a<=18)

In [109]: all=c1&c2

In [110]: a[all]
Out[110]: array([14, 15, 16, 17])   # the values

In [111]: all.nonzero()
Out[111]: (array([4, 5, 6, 7]),)    # the coordinates

Hope that helps,

Francesc Alted

More information about the Numpy-discussion mailing list