【问题标题】:Using a numpy array to assign values to another array使用 numpy 数组将值分配给另一个数组
【发布时间】:2017-01-29 14:00:39
【问题描述】:

我有以下 numpy 数组 matrix

matrix = np.zeros((3,5), dtype = int)

array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

假设我也有这个 numpy 数组 indices

indices = np.array([[1,3], [2,4], [0,4]])

array([[1, 3],
       [2, 4],
       [0, 4]]) 

问题:如何将1s 分配给matrix 中的元素,其中它们的索引由indices 数组指定。预计会采用矢量化实现。

为了更清楚,输出应如下所示:

    array([[0, 1, 0, 1, 0], #[1,3] elements are changed
           [0, 0, 1, 0, 1], #[2,4] elements are changed
           [1, 0, 0, 0, 1]]) #[0,4] elements are changed

【问题讨论】:

    标签: python arrays numpy indexing vectorization


    【解决方案1】:

    这涉及循环,因此对于大型数组可能不是很有效

    for i in range(len(indices)):
        matrix[i,indices[i]] = 1
    
    > matrix
     Out[73]: 
    array([[0, 1, 0, 1, 0],
          [0, 0, 1, 0, 1],
          [1, 0, 0, 0, 1]])
    

    【讨论】:

      【解决方案2】:

      这是使用NumPy's fancy-indexing 的一种方法-

      matrix[np.arange(matrix.shape[0])[:,None],indices] = 1
      

      说明

      我们使用np.arange(matrix.shape[0]) 创建行索引 -

      In [16]: idx = np.arange(matrix.shape[0])
      
      In [17]: idx
      Out[17]: array([0, 1, 2])
      
      In [18]: idx.shape
      Out[18]: (3,)
      

      列索引已经给出为indices -

      In [19]: indices
      Out[19]: 
      array([[1, 3],
             [2, 4],
             [0, 4]])
      
      In [20]: indices.shape
      Out[20]: (3, 2)
      

      我们来做个行列索引的形状示意图,idxindices-

      idx     (row) :      3 
      indices (col) :  3 x 2
      

      为了使用行和列索引来索引输入数组matrix,我们需要使它们可以相互广播。一种方法是在idx 中引入一个新轴,通过将元素推入第一个轴并允许使用idx[:,None] 作为最后一个轴,使其成为2D,如下所示 -

      idx     (row) :  3 x 1
      indices (col) :  3 x 2
      

      在内部,idx 将被广播,就像这样 -

      In [22]: idx[:,None]
      Out[22]: 
      array([[0],
             [1],
             [2]])
      
      In [23]: indices
      Out[23]: 
      array([[1, 3],
             [2, 4],
             [0, 4]])
      
      In [24]: np.repeat(idx[:,None],2,axis=1) # indices has length of 2 along cols
      Out[24]: 
      array([[0, 0],  # Internally broadcasting would be like this
             [1, 1],
             [2, 2]]) 
      

      因此,来自idx 的广播元素将用作来自indices 的行索引和列索引,用于索引到matrix 以设置其中的元素。因为,我们有 -

      idx = np.arange(matrix.shape[0]),

      因此,我们最终会得到 -

      matrix[np.arange(matrix.shape[0])[:,None],indices] 用于设置元素。

      【讨论】:

      • 我用你的方法完成了我的工作,但实现对我来说有点模糊。您能否详细说明所执行的操作?
      • @akilat90 看看添加的 cmets 是否有意义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 2016-06-04
      相关资源
      最近更新 更多