Home > Back-end >  Multi-line numpy where() condition
Multi-line numpy where() condition

Time:02-19

Folks, To avoid a for loop, I am working on a vector-based way of doing the following:

Array_1 has float values ranging from -3.0 to 3.0 and walks randomly between these extremes.

I want to create Array_2 to be something like this:

Array_2 = np.where((Array_1[row] > 2) & (Array_1[row-1] < 2),1,0)

HOW can I accomplish this within my np.where() condition? Ultimately I want to avoid a for-loop.

Any ideas?

CodePudding user response:

You don't actually need to use np.where, you apply np.roll on the input to construct a helper array that will let you access the original array with an offset

>>> x = np.random.uniform(-3, 3, 20)
array([ 0.87457789,  2.78372382,  2.99091498,  1.13015817,  2.08503683,
        1.48561846, -1.30544443, -1.34806256,  0.46013052,  1.71623744,
       -1.11043827, -0.14515713,  2.81997195,  0.62134152, -1.95262578,
       -0.93686073,  0.56367685,  1.96501996,  0.59958956,  2.6594141 ])

Roll x with an offset of 1:

>>> (x > 2)*(np.roll(x, 1) < 2)
array([False,  True, False, False,  True, False, False, 
       False, False, False, False, False,  True, False, 
       False, False, False, False, False,  True])

If you want to coerce the resulting array to integers or floating points:

>>> (x > 2)*(np.roll(x, 1) < 2)*1
array([0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1])
  • Related