python - 将非数字元组转换为 numpy 矩阵

标签 python numpy matrix

我试图通过一个非常大的元组列表来表示一个邻接矩阵。我将如何在 numpy 矩阵或 scipy.sparse 矩阵中表示此列表,以便使用像 igraph 或 networkx 这样的包?

[('b', 'c'),
 ('b', 'a'),
 ('c', 'd'),
 ('c', 'a'),
 ('c', 'b'),
 ('a', 'b'),
 ('a', 'c')]

如果这是重复的,我深表歉意,但我找不到任何关于如何将非数字元组转换为邻接矩阵的文档。

最佳答案

您可以使用 np.unique 将您的节点转换为索引:

>>> adj = [('b', 'c'),
...        ('b', 'a'),
...        ('c', 'd'),
...        ('c', 'a'),
...        ('c', 'b'),
...        ('a', 'b'),
...        ('a', 'c')]
>>> node_names, adj_idx = np.unique(adj, return_inverse=True)
>>> node_names
array(['a', 'b', 'c', 'd'], 
      dtype='|S1')
>>> adj_idx = adj_idx.reshape(-1, 2)
>>> adj_idx
array([[1, 2],
       [1, 0],
       [2, 3],
       [2, 0],
       [2, 1],
       [0, 1],
       [0, 2]])

据此,您可以将密集邻接矩阵构造为:

>>> adj_matrix = np.zeros((len(node_names),)*2)
>>> adj_matrix[adj_idx[:, 0], adj_idx[:, 1]] = 1
>>> adj_matrix
array([[ 0.,  1.,  1.,  0.],
       [ 1.,  0.,  1.,  0.],
       [ 1.,  1.,  0.,  1.],
       [ 0.,  0.,  0.,  0.]])

或稀疏格式为:

>>> sps_adj_mat = sps.coo_matrix((np.ones(shape=(len(adj_idx),)),
...                               (adj_idx[:, 0], adj_idx[:, 1])),
...                              shape=(len(node_names),)*2)
>>> sps_adj_mat
<4x4 sparse matrix of type '<type 'numpy.float64'>'
    with 7 stored elements in COOrdinate format>
>>> sps_adj_mat.A
array([[ 0.,  1.,  1.,  0.],
       [ 1.,  0.,  1.,  0.],
       [ 1.,  1.,  0.,  1.],
       [ 0.,  0.,  0.,  0.]])

关于python - 将非数字元组转换为 numpy 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324774/

相关文章:

Python 显式 next() 比多线程生产者-消费者范式中的 for 循环慢

python - 允许 python 子进程的多个输入

python - 在 Python 中求解非线性方程组 (scipy.optimize.fsolve)

python - 最大化复杂多变量函数的计算有效方法

matrix - 是否可以编写一个可以转置矩阵的rust宏?

python - 属性错误 : 'str' object has no attribute 'isoformat'

python - 如何使用 python 匹配文本文件中的单词?

python - 箱线图屏蔽数组

python - 叠加两个 pandas Dataframes 或 numpy 数组并创建一个键值字典

algorithm - 我如何将 IF 语句应用于矩阵的所有行(Matlab)