numpy 函数将数组元素设置为给定索引列表的值

问题描述 投票:0回答:3

我正在寻找一个 numpy 函数,它的作用相当于:

indices = set([1, 4, 5, 6, 7])
zero    = numpy.zeros(10)
for i in indices:
    zero[i] = 42
python numpy variable-assignment indices
3个回答
32
投票

你可以给它一个索引列表:

indices = [1, 4, 5, 6, 7]
zero = numpy.zeros(10)
zero[indices] = 42

4
投票

如果你有一个 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.]]])

0
投票

这也可以使用 np.insert:

indices = [1, 4, 5, 6, 7]
zero = numpy.zeros(10)
new_array = np.insert(zero, indices, 42)
© www.soinside.com 2019 - 2024. All rights reserved.