[英]numpy function to set elements of array to a value given a list of indices
I'm looking for a numpy function that will do the equivalent of:我正在寻找一个 numpy 函数,它可以执行以下操作:
indices = set([1, 4, 5, 6, 7])
zero = numpy.zeros(10)
for i in indices:
zero[i] = 42
You can just give it a list of indices:你可以给它一个索引列表:
indices = [1, 4, 5, 6, 7]
zero = numpy.zeros(10)
zero[indices] = 42
If you have an ndarray:如果你有一个 ndarray:
>>> x = np.zeros((3, 3, 3))
>>> y = [0, 9, 18]
>>> x
array([[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]])
>>> np.put(x, y, 1)
>>> x
array([[[ 1., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 1., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 1., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.