Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 260
memyself Avatar asked Mar 20 '12 19:03

memyself


People also ask

How do you remove the nth element from an array in Python?

To remove every nth element of a list in Python, utilize the Python del keyword to delete elements from the list and slicing. For your slice, you want to pass n for the slice step size. For example, if you have a list and you to remove every 2nd element, you would delete the slice defined by [1::2] as shown below.

How do you find the most frequent value in an array?

Steps to find the most frequency value in a NumPy array:Create a NumPy array. Apply bincount() method of NumPy to get the count of occurrences of each element in the array. The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).

Which is more efficient a Python list or a NumPy array?

As predicted, we can see that NumPy arrays are significantly faster than lists.


1 Answers

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
like image 52
Sven Marnach Avatar answered Oct 26 '22 23:10

Sven Marnach