【问题标题】:How to replace non-zero elements of a (0,1) numpy array by it's column/ row indices without using a loop?如何在不使用循环的情况下用它的列/行索引替换 (0,1) numpy 数组的非零元素?
【发布时间】:2021-03-22 14:10:11
【问题描述】:

我有一个 0 和 1 的 numpy 数组。

def random_array(p):
    return np.random.choice(2, 6, p=[p, 1-p])
my_matrix = np.array([random_array(j) for j in np.random.uniform(0.3, 1.0, 4)])

我可以得到所有零零元素的索引为np.nonzero(my_matrix)。请您帮我将所有这些索引分配给它所在的列号(即使列索引也可以,我们从 0 而不是 1 开始)。例如,

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

在这里,所有的 1 都被替换为列号。因此,这是一个所有非零元素都是 1 的矩阵。如果你能找到 column 的索引,那么它也将是 fibulas,因为我可以通过添加 1 得到相同的结果。

注意:我不希望为此任务使用任何循环。

【问题讨论】:

    标签: python arrays numpy matrix


    【解决方案1】:

    如果我理解得很好,您想用它们的列索引(从 1 而不是 0 开始)替换所有非零元素,对吗? 然后你可以这样做:

    idx = np.nonzero(my_matrix)
    my_matrix[idx[0], idx[1]] = idx[1]+1
    

    【讨论】:

      【解决方案2】:

      您可以将您的数组与另一个包含相应行/列索引的相同大小的数组相乘:

      ## Dummy data
      #  Array size
      s = (6,4)
      #  Axis along which we need to calculate the index:
      a = 0
      #  Random binary array
      x = np.random.rand(*s).round()
      
      #  Get the index along one axis using broadcasting (starting with 1)
      x = x*(np.expand_dims(range(s[a]),len(s)-a-1)+1)
      

      【讨论】:

        【解决方案3】:
        In [169]: def random_array(p):
             ...:     return np.random.choice(2, 6, p=[p, 1-p])
             ...: my_matrix = np.array([random_array(j) for j in np.random.uniform(0.3, 1.0, 4)])
        In [170]: my_matrix
        Out[170]: 
        array([[0, 0, 0, 0, 0, 0],
               [0, 1, 1, 0, 0, 0],
               [0, 0, 1, 1, 0, 1],
               [1, 1, 0, 0, 1, 0]])
        

        只需乘以范围索引。通过广播 (6,) arange 对列很好:

        In [171]: np.arange(1,7)*my_matrix
        Out[171]: 
        array([[0, 0, 0, 0, 0, 0],
               [0, 2, 3, 0, 0, 0],
               [0, 0, 3, 4, 0, 6],
               [1, 2, 0, 0, 5, 0]])
        

        对于行

        In [172]: np.arange(1,5)[:,None]*my_matrix
        Out[172]: 
        array([[0, 0, 0, 0, 0, 0],
               [0, 2, 2, 0, 0, 0],
               [0, 0, 3, 3, 0, 3],
               [4, 4, 0, 0, 4, 0]])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-24
          • 1970-01-01
          • 2017-11-10
          • 2020-01-04
          • 2018-10-15
          • 1970-01-01
          • 1970-01-01
          • 2020-08-30
          相关资源
          最近更新 更多