如何基于另一个数组创建一个数组?

Tin*_*hiu 5 python arrays numpy

我是 python 新手,我想尝试基于另一个数组创建一个数组。

如果我有一个像这样的数组:

array = [[1, 1], [1, 2], [2, 2], [3, 2], [3, 3], [4, 2], [5, 1], [5, 3]]
Run Code Online (Sandbox Code Playgroud)

那么如果要基于数组创建矩阵,如果对应位置有一个值,如下所示:在数组中,第一个数字代表矩阵中的行,第二个数字代表矩阵中的列,例如 [1, 1]表示row1、column有值,则=1;数组中没有 [1,3] 意味着第 1 行和第 3 列等于 0。所以我希望结果如下:

      col1 col2 col3
row1 [ 1    1    0 ]
row2 [ 0    1    0 ]
row3 [ 0    1    1 ]
row4 [ 0    1    0 ]
row5 [ 1    0    1 ]

result = [[1, 1, 0], [0, 1, 0], [0, 1, 1], [0, 1, 0], [1, 0, 1]]
Run Code Online (Sandbox Code Playgroud)

请注意,数组中的值只是一个示例,而不是矩阵的确切位置。

我尝试过将值插入空数组中,但很难在矩阵中识别相应的位置。

另一个例子是:

array =[[4, 3], [4, 23], [5, 308], [5, 432], [8, 432], [8, 429]]
Run Code Online (Sandbox Code Playgroud)

矩阵如下:

      col1 col2 col3 col4 col5
row1 [ 1    1    0    0    0  ]
row2 [ 0    0    1    1    0  ]
row3 [ 0    0    0    1    1  ]

Run Code Online (Sandbox Code Playgroud)

不确定问题描述是否清楚。

Cap*_*jan 4

第一个数组(名为array)称为稀疏二进制矩阵表示。第二个数组(名为result)称为密集二进制矩阵表示。如果您想预先将值转换为排名(同时考虑重复项),您可以使用该numpy.unique函数。因此,完整的程序是:

from scipy.sparse import csr_matrix
from numpy import unique

array = [[1, 1], [1, 2], [2, 2], [3, 2], [3, 3], [4, 2], [5, 1], [5, 3]]

r_unique, rows = unique([v[0] for v in array], return_inverse=True)
c_unique, cols = unique([v[1] for v in array], return_inverse=True)
values = [1] * len(array)
n = len(r_unique)
m = len(c_unique)

result = csr_matrix((values, (rows, cols)), shape=(n, m)).toarray()
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为r_unique是 中一维的所有唯一数字的集合,它是相应维度中array的大小。然后包含从到其在此维度内的映射。这同样适用于和。resultrowsnumberrankcolsc_unique