Splitting arrays into chunks that satisfy a condition?

I have three arrays (x,y,z). I want plot x vs y and draw the line segments differently depending on whether or not z is positive or negative. So I'm trying to split the x,y arrays into chunks depending on the value of z. Using numpy.where, I can find the indeces in z that satisfy a condition but I can't figure out an efficient way (other than brute force) to split the array up into continuous chunks. Does anyone know of a numpy trick that would help with this?

Here's a simple example:

# index: 0 1 2 3 4 5 6 7 8 9
z=numpy.array([-1,-1,-1, 1, -1,-1,-1, 1,1,1] )
x=numpy.array([-2,-3,-4, 2, -5,-6,-7, 3,4,5] )

# Want: xneg = [ x[0:3], x[4:7] ], xpos = [ x[3:4], x[7:10] ]
xneg = [ [-2,-3,-4], [-5,-6,-7] ]
xpos = [ [ 2 ], [ 3, 4, 5 ] ]

idxneg = numpy.where( z < 0 )[0]
# == [ 0,1,2, 4,5,6 ]
idxpos = numpy.where( z >= 0 )[0]
# == [ 3, 7,8,9 ]

Thanks,
Ted

One way I would go about it is to do this:

z1 = numpy.where(z < 0, z, numpy.nan)
z2 = numpy.where(z >= 0, z, numpy.nan)

And then plot those against x. matplotlib ignores nans and would break up
the line where-ever a nan shows up (assuming that is the effect you want).

Cheers!
Ben Root

ยทยทยท

On Fri, Aug 2, 2013 at 1:36 PM, Drain, Theodore R (392P) < theodore.r.drain@...369...> wrote:

I have three arrays (x,y,z). I want plot x vs y and draw the line
segments differently depending on whether or not z is positive or negative.
So I'm trying to split the x,y arrays into chunks depending on the value
of z. Using numpy.where, I can find the indeces in z that satisfy a
condition but I can't figure out an efficient way (other than brute force)
to split the array up into continuous chunks. Does anyone know of a numpy
trick that would help with this?

Here's a simple example:

# index: 0 1 2 3 4 5 6 7 8 9
z=numpy.array([-1,-1,-1, 1, -1,-1,-1, 1,1,1] )
x=numpy.array([-2,-3,-4, 2, -5,-6,-7, 3,4,5] )

# Want: xneg = [ x[0:3], x[4:7] ], xpos = [ x[3:4], x[7:10] ]
xneg = [ [-2,-3,-4], [-5,-6,-7] ]
xpos = [ [ 2 ], [ 3, 4, 5 ] ]

idxneg = numpy.where( z < 0 )[0]
# == [ 0,1,2, 4,5,6 ]
idxpos = numpy.where( z >= 0 )[0]
# == [ 3, 7,8,9 ]

Thanks,
Ted