如何解决使用指定索引重塑数组
有没有更好的方法来做到这一点?喜欢用 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]]
解决方法
另一种方式:
shape = (rows,cols)
arr = np.zeros(shape)
arr[np.unravel_index(target,shape)] = 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
之类的 dtype 或除 bool
之外的任何其他适合您需求的类型。
此处显示的方法甚至适用于您的列表示例,以提高效率。即使您将 target
转换为 set
,您也正在使用 O(N)
执行 N = rows * cols
查找。相反,您只需要 M
赋值,无需查找,使用 M = len(target)
:
x = [0] * (rows * cols)
for i in target:
x[i] = 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。