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?
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.
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).
As predicted, we can see that NumPy arrays are significantly faster than lists.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With