Home > Mobile >  How do I roll a list or numpy array until a certain condition is met?
How do I roll a list or numpy array until a certain condition is met?

Time:02-11

I have a numpy array

import numpy as np
arr = np.array([70, 80, 90, 100, 110, 120, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                 11, 12, 1, 2, 3, 4, 5, 6])

Here, for example, I want to roll the array until one (of the 1s) is at the start and then record what the shift was, but you could image some other arbitrary condition on the roll.

arr_expected = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 70, 80, 90, 100, 110, 120])
shift_of_arr = ?

How do I roll the array until some condition is met?

Can it be done without a for loop and if so how?

For context: These are monotonically increasing values, but not necessarily with the same interval.

Thanks as ever!

CodePudding user response:

NB. I slightly modified your input to make it non ambiguous (added 10 to the first values to be able to see the direction of rolling). Obviously the answer would work the same on the original data.

You can use numpy.argmax on a boolean array to get the position of the first 1, then use numpy.roll:

arr = np.array([70, 80, 90, 100, 110, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                 11, 12, 1, 2, 3, 4, 5, 6])

n = np.argmax(arr==1) # 6
arr2 = np.roll(arr, -n)

output:

array([  1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,   1,
         2,   3,   4,   5,   6,  70,  80,  90, 100, 110])
  • Related