Home > Software engineering >  numpy change value of cyclic range of elements
numpy change value of cyclic range of elements

Time:06-23

I have an array of elements, for simplicity:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]).
Starting with 0, every nth element, I'd like to change the value of the next m elements.
For example: n=5; m=2 and I'd like to set the elements to 100.

The output should be something like:
array([ 100, 100, 2, 3, 4, 100, 100, 7, 8, 9, 100, 100, 12, 13, 14, 100, 100, 17, 18, 19])

is this a numpy way to do it in one line (with indices)? or only by looping or list comprehension - which will be slower..?

CodePudding user response:

The following could do the job

arr.reshape((-1, n))[:, :m] = 100
  • Related