使用指定索引重塑数组

Reshaping array with specified indices

有什么更好的方法吗?喜欢用 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]]

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

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

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

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

如果您想要实际的零和一,请使用 np.uint8 之类的数据类型或除 bool.

之外的任何其他适合您需要的数据类型

此处显示的方法甚至可以应用于您的列表示例以提高效率。即使您将 target 变成了 set,您也在执行 O(N) 查找,使用 N = rows * cols。相反,您只需要 M 没有查找的分配, M = len(target):

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

另一种方式:

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