gpt4 book ai didi

python - Numpy 重新索引前 N 个自然数

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:09 26 4
gpt4 key购买 nike

我有一个索引非常稀疏的矩阵(行和列中的最大值都超过 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]])

关于python - Numpy 重新索引前 N 个自然数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51082879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com