其他分享
首页 > 其他分享> > numpy重新索引到前N个自然数

numpy重新索引到前N个自然数

作者:互联网

我有一个矩阵,索引很稀疏(行和列中的最大值都超过130000),但是实际上只有少数几行/列具有非零值.

因此,我想通过前N个自然数将行索引和列索引移位为仅表示非零索引.

在视觉上,我想要一个这样的示例矩阵

1 0 1
0 0 0
0 0 1

看起来像这样

1 1
0 1

但前提是行/列中的所有值均为零.
由于我确实具有稀疏格式的矩阵,因此我可以简单地创建一个字典,通过递增的计数器存储每个值(分别用于行和矩阵),并获得结果.

row_dict = {}
col_dict = {}
row_ind = 0
col_ind = 0

# el looks like this: (row, column, value)
for el in sparse_matrix:
    if el[0] not in row_dict.keys():
        row_dict[el[0]] = row_ind
        row_ind += 1
    if el[1] not in col_dict.keys():
        col_dict[el[1]] = col_ind
        col_ind += 1
# now recreate matrix with new index

但是我一直在寻找NumPy的内部函数.还要注意,我真的不知道该如何措辞,因此很可能有一个我不知道的重复内容.任何朝着正确方向的指针都值得赞赏.

解决方法:

您可以使用np.unique:

>>> import numpy as np 
>>> from scipy import sparse
>>>
>>> A = np.random.randint(-100, 10, (10, 10)).clip(0, None)
>>> A
array([[6, 0, 5, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 7, 0, 0, 0, 0, 4, 9],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 4, 0],
       [9, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 4, 0, 0, 0, 0, 0, 0]])
>>> B = sparse.coo_matrix(A)
>>> B
<10x10 sparse matrix of type '<class 'numpy.int64'>'
        with 8 stored elements in COOrdinate format>
>>> runq, ridx = np.unique(B.row, return_inverse=True)
>>> cunq, cidx = np.unique(B.col, return_inverse=True)
>>> C = sparse.coo_matrix((B.data, (ridx, cidx)))
>>> C.A
array([[6, 5, 0, 0, 0],
       [0, 0, 7, 4, 9],
       [0, 0, 0, 4, 0],
       [9, 0, 0, 0, 0],
       [0, 0, 4, 0, 0]])

标签:matrix-indexing,sparse-matrix,python,numpy
来源: https://codeday.me/bug/20191108/2010217.html