how to replace every n-th value of an array in python most efficiently?

旧时模样 提交于 2021-02-04 18:08:26

问题


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)


REPLACE_EVERY_Nth = 100
REPLACE_WITH = 120
c = 0

for index, item in enumerate(y):
    c += 1
    if (c % REPLACE_EVERY_Nth == 0):
        y[index] = REPLACE_WITH

So basically I generate a bunch of numbers from 1 to MAX_SIZE-1, and then I want to replace every REPLACE_EVERY_Nth element with REPLACE_WITH. This works fine but I guess it could be somehow done without using enumerate?

I was thinking something like this (which I know is wrong, because I replace the original y with the indices of y):

y = map(lambda x: REPLACE_WITH if not x%REPLACE_EVERY_Nth else x, range(len(y)))

is there a way to do modulo on the indices but replace the values?


回答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



回答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



回答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


来源:https://stackoverflow.com/questions/9793731/how-to-replace-every-n-th-value-of-an-array-in-python-most-efficiently

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!