这是我的输入
{(0, 1), (2, 1), (0, 0), (1, 1), (1, 0)}
这些是大小为N=5的矩阵中的1的位置。我想要的输出是
[[1,1,0,0,0],
[1,1,0,0,0],
[0,1,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
有没有一种有效的方法来进行转换?也许是一个内置的numpy函数?创建一个零矩阵,然后循环遍历位置向量,以推入1,对我来说似乎不是很有效。
我对输出的最终目标是将其提供给matplotlib的matshow()函数。
3条答案
按热度按时间pkbketx91#
@Ansagara的答案可以完成这项工作,但需要一个for循环。它也可以在没有for循环的情况下完成,如下所示。对于较大的
positions
阵列,这可以更好地扩展。这就给了
cld4siwp2#
您可以利用numpy.zeros()函数创建一个零矩阵,然后根据位置向量将值1分配给相应的位置。
下面是演示这种方法的示例代码:
输出:
ncgqoxb03#
使用numpy广播来设置value.it可能比for循环更好。
首先,让我们得到列的每行集合,它是“dic”。
0 2 1是行,0:[1,0]是第一行索引的列索引。
2:[1]是第三行索引的列索引。
1:[1,0]是第二行索引的列索引。
有了dic,你可以使用boardcast来设置矩阵中的值