【问题标题】:Reshaping array with specified indices使用指定索引重塑数组
【发布时间】:2021-06-19 16:12:11
【问题描述】:

有没有更好的方法来做到这一点?就像用 numpy 函数替换列表理解一样?我假设对于少量元素,差异是微不足道的,但对于较大的数据块,它需要太多时间。

>>> rows = 3
>>> cols = 3
>>> target = [0, 4, 7, 8] # each value represent target index of 2-d array converted to 1-d
>>> x = [1 if i in target else 0 for i in range(rows * cols)]
>>> arr = np.reshape(x, (rows, cols))
>>> arr 
[[1 0 0]
 [0 1 0]
 [0 1 1]]

【问题讨论】:

    标签: python arrays numpy reshape


    【解决方案1】:

    由于x 来自一个范围,您可以索引一个零数组来设置零:

    x = np.zeros(rows * cols, dtype=bool)
    x[target] = True
    x = x.reshape(rows, cols)
    

    或者,您可以预先创建适当的形状并分配给 raveled 数组:

    x = np.zeros((rows, cols), dtype=bool)
    x.ravel()[target] = True
    

    如果您想要实际的 0 和 1,请使用 np.uint8 之类的 dtype 或除 bool 以外的任何其他适合您需求的类型。

    此处显示的方法甚至适用于您的列表示例,以提高效率。即使您将target 转换为set,您也正在使用N = rows * cols 执行O(N) 查找。相反,您只需要 M 分配而无需查找,使用 M = len(target)

    x = [0] * (rows * cols)
    for i in target:
        x[i] = 1
    

    【讨论】:

      【解决方案2】:

      另一种方式:

      shape = (rows, cols)
      arr = np.zeros(shape)
      arr[np.unravel_index(target, shape)] = 1
      

      【讨论】:

      • 通常比x.ravel()[target] = True 更健壮,虽然使用新分配的x,但我的版本可能会快一点。
      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 2015-11-23
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      相关资源
      最近更新 更多