gpt4 book ai didi

python - 从逻辑矩阵到集合列表的最快方法

转载 作者:太空狗 更新时间:2023-10-30 00:54:28 24 4
gpt4 key购买 nike

我需要将稀疏逻辑矩阵转换为集合列表,其中每个列表 [i] 包含列 [i] 具有非零值的行集合。以下代码有效,但我想知道是否有更快的方法来执行此操作。我使用的实际数据大约是 6000x6000,比这个例子稀疏得多。

import numpy as np

A = np.array([[1, 0, 0, 0, 0, 1],
[0, 1, 1, 1, 1, 0],
[1, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 0, 1],
[1, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 0]])

rows,cols = A.shape

C = np.nonzero(A)
D = [set() for j in range(cols)]

for i in range(len(C[0])):
D[C[1][i]].add(C[0][i])

print D

最佳答案

如果将稀疏数组表示为 csc_matrix ,您可以使用 indicesindptr 属性来创建集合。

例如,

In [93]: A
Out[93]:
array([[1, 0, 0, 0, 0, 1],
[0, 1, 1, 1, 1, 0],
[1, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 0, 1],
[1, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 0]])

In [94]: from scipy.sparse import csc_matrix

In [95]: C = csc_matrix(A)

In [96]: C.indptr
Out[96]: array([ 0, 5, 8, 12, 16, 20, 23], dtype=int32)

In [97]: C.indices
Out[97]: array([0, 2, 3, 4, 5, 1, 3, 4, 1, 2, 6, 7, 1, 3, 4, 6, 1, 2, 6, 7, 0, 2, 3], dtype=int32)

In [98]: D = [set(C.indices[C.indptr[i]:C.indptr[i+1]]) for i in range(C.shape[1])]

In [99]: D
Out[99]:
[{0, 2, 3, 4, 5},
{1, 3, 4},
{1, 2, 6, 7},
{1, 3, 4, 6},
{1, 2, 6, 7},
{0, 2, 3}]

对于数组列表而不是集合,不要调用set():

In [100]: [C.indices[C.indptr[i]:C.indptr[i+1]] for i in range(len(C.indptr)-1)]
Out[100]:
[array([0, 2, 3, 4, 5], dtype=int32),
array([1, 3, 4], dtype=int32),
array([1, 2, 6, 7], dtype=int32),
array([1, 3, 4, 6], dtype=int32),
array([1, 2, 6, 7], dtype=int32),
array([0, 2, 3], dtype=int32)]

关于python - 从逻辑矩阵到集合列表的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37758740/

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