Python 使用指定索引重塑数组
有没有更好的办法?比如用numpy函数替换列表理解?我假设对于少量的元素,差异是微不足道的,但是对于较大的数据块,它需要花费太多的时间Python 使用指定索引重塑数组,python,arrays,numpy,reshape,Python,Arrays,Numpy,Reshape,有没有更好的办法?比如用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 el
>>> 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
来自一个范围,因此您可以索引一个零数组来设置1:
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
如果您想要实际的0和1,请使用像np.uint8
这样的数据类型,或者除bool
之外的任何适合您需要的数据类型
这里显示的方法甚至可以应用于列表示例,以提高效率。即使将目标
转换为集合
,也会使用N=rows*cols
执行O(N)
查找。相反,您只需要使用M=len(目标)
,不进行查找的M
分配:
另一种方式:
shape = (rows, cols)
arr = np.zeros(shape)
arr[np.unravel_index(target, shape)] = 1
通常比
x.ravel()[target]=True更健壮,尽管使用新分配的x
,我的版本可能会快一点。
shape = (rows, cols)
arr = np.zeros(shape)
arr[np.unravel_index(target, shape)] = 1