numpy 将一组位置向量转换为一个矩阵

yqlxgs2m  于 2023-06-29  发布在  其他
关注(0)|答案(3)|浏览(140)

这是我的输入

{(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()函数。

pkbketx9

pkbketx91#

@Ansagara的答案可以完成这项工作,但需要一个for循环。它也可以在没有for循环的情况下完成,如下所示。对于较大的positions阵列,这可以更好地扩展。

import numpy as np

positions = {(0, 1), (2, 1), (0, 0), (1, 1), (1, 0)}
N = 5

# Create a matrix of zeros
matrix = np.zeros((N, N), dtype=int)

# Assign 1 to the positions based on the position vectors
positions = np.asarray(list(positions))
matrix[positions[:,0], positions[:,1]] = 1

print(matrix)

这就给了

[[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]]
cld4siwp

cld4siwp2#

您可以利用numpy.zeros()函数创建一个零矩阵,然后根据位置向量将值1分配给相应的位置。
下面是演示这种方法的示例代码:

import numpy as np

positions = {(0, 1), (2, 1), (0, 0), (1, 1), (1, 0)}
N = 5

# Create a matrix of zeros
matrix = np.zeros((N, N), dtype=int)

# Assign 1 to the positions based on the position vectors
for pos in positions:
    matrix[pos] = 1

print(matrix)

输出:

[[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]]
ncgqoxb0

ncgqoxb03#

使用numpy广播来设置value.it可能比for循环更好。
首先,让我们得到列的每行集合,它是“dic”。
0 2 1是行,0:[1,0]是第一行索引的列索引。
2:[1]是第三行索引的列索引。
1:[1,0]是第二行索引的列索引。
有了dic,你可以使用boardcast来设置矩阵中的值

dic: {0: [1, 0], 2: [1], 1: [1, 0]}
import numpy as np

kk = [(0, 1), (2, 1), (0, 0), (1, 1), (1, 0)]
# kk = sorted(kk.__iter__(), key=lambda j:j[0])
dic = {}
for i in kk:
    if i[0] not in dic.keys():
        dic[i[0]] = [i[1]]
    else:
        dic[i[0]].append(i[1])

zer = np.zeros((6,6))
for key, val in dic.items():
    zer[key, val] = 1
zer
array([[1., 1., 0., 0., 0., 0.],
       [1., 1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]])

相关问题