Skip to content Skip to sidebar Skip to footer

How To Replace Every N-th Value Of An Array In Python Most Efficiently?

I was wondering whether there is a more pythonic (and efficient) way of doing the following: MAX_SIZE = 100 nbr_elements = 10000 y = np.random.randint(1, MAX_SIZE, nbr_elements)

Solution 1:

Use a slicing with REPLACE_EVERY_Nth as step value:

y[::REPLACE_EVERY_Nth] = REPLACE_WITH

This is slightly different from your code, since it will start with the very first item (i.e. index 0). To get exactly what your code does, use

y[REPLACE_EVERY_Nth - 1::REPLACE_EVERY_Nth] = REPLACE_WITH

Solution 2:

You can simply use range(start, end, step) for your loop:

for index in range(0,len(y),REPLACE_EVERY_Nth):
    y[index] = REPLACE_WITH

Solution 3:

I think following solution can be applied without having any issues:

for index in xrange(0, len(y), REPLACE_EVERY_Nth):
    y[index] = REPLACE_WITH

Post a Comment for "How To Replace Every N-th Value Of An Array In Python Most Efficiently?"