Skip to content Skip to sidebar Skip to footer

Numpy: Replace Every N Element In The First Half Of An Array

If I have a numpy array and want to replace every nth element to 0 in the first half of the array( no change in the second half), how can I do this efficiently? Now my code is not

Solution 1:

Just use a[:a.size//2:n] = 0. e.g.:

a = np.ones(10)
a[:a.size//2:2] = 0
a
array([ 0.,  1.,  0.,  1.,  0.,  1.,  1.,  1.,  1.,  1.])

Another example:

a = np.ones(20)
n = 3
a[:a.size//2:n] = 0

a
array([ 0.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  1.,  1.,
    1.,  1.,  1.,  1.,  1.,  1.,  1.])

Solution 2:

You could slice the array by doing something like:

import numpy as np
# make an array of 11 elements filled with zeros
my_arr = np.zeros(11)

# get indexes to change in the array. range is: range(start, stop[, step])
a = range(0, 5, 2)
# print the original array
print my_arr 

# Change the array
my_arr[a] = 1

# print the changes
print my_arr

Outputs:

array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
array([ 0.,  1.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

Post a Comment for "Numpy: Replace Every N Element In The First Half Of An Array"