代码之家  ›  专栏  ›  技术社区  ›  user

使用索引列表对numpy数组的元素执行操作

  •  0
  • user  · 技术社区  · 7 年前

    我有numpy数组和两个python索引列表,它们的位置可以将数组元素增加一个。numpy是否有一些方法可以在不使用 for 循环?

    我目前执行缓慢:

    a = np.zeros([4,5])
    xs = [1,1,1,3]
    ys = [2,2,3,0]
    
    for x,y in zip(xs,ys): # how to do it in numpy way (efficiently)?
        a[x,y] += 1
    
    print(a)
    

    输出:

    [[0. 0. 0. 0. 0.]
     [0. 0. 2. 1. 0.]
     [0. 0. 0. 0. 0.]
     [1. 0. 0. 0. 0.]]
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   Tomas Farias    7 年前

    np.add.at 只需将两个索引作为单个2d数组/列表传递即可:

    a = np.zeros([4,5])
    xs = [1, 1, 1, 3]
    ys = [2, 2, 3, 0]
    
    np.add.at(a, [xs, ys], 1) # in-place
    print(a)
    
    array([[0., 0., 0., 0., 0.],
           [0., 0., 2., 1., 0.],
           [0., 0., 0., 0., 0.],
           [1., 0., 0., 0., 0.]])
    
        2
  •  1
  •   lenik    7 年前
    >>> a = np.zeros([4,5])
    >>> xs = [1, 1, 1, 3]
    >>> ys = [2, 2, 3, 0]
    >>> a[[xs,ys]] += 1
    >>> a
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  1.,  1.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.,  0.]])