Numpy: Replace every n element in the first half of an array

╄→гoц情女王★ 提交于 2021-01-27 14:38:08

问题


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 efficient enough: for i in xrange(1,half,n): s[i] = 0


回答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.])



回答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.])


来源:https://stackoverflow.com/questions/35439570/numpy-replace-every-n-element-in-the-first-half-of-an-array

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