获取networkx.MultiDiGraph的邻接矩阵

问题描述 投票:0回答:1

我想获得

networkx.MultiDiGraph
的邻接矩阵。我的代码如下所示:

import numpy as np
import networkx as nx
np.random.seed(123)

n_samples = 10


uv = [
    (1, 2),
    (2, 3),
    (3, 4),
    (4, 5),
    (5, 6)
]


G = nx.MultiDiGraph()

for u, v in uv:
    weights = np.random.uniform(0, 1, size=n_samples)
    G.add_edges_from([(u, v, dict(sample_id=s+1, weight=weights[s])) for s in range(n_samples)])

A = nx.to_numpy_array(G=G, nodelist=list(G.nodes))

正如 docs 所言,此类图的

nx.to_numpy_array()
默认值是对多条边的权重求和。 因此,输出如下所示:

[[0.         5.44199353 0.         0.         0.         0.        ]
 [0.         0.         4.12783997 0.         0.         0.        ]
 [0.         0.         0.         5.37945594 0.         0.        ]
 [0.         0.         0.         0.         4.95418265 0.        ]
 [0.         0.         0.         0.         0.         5.18942126]
 [0.         0.         0.         0.         0.         0.        ]]

我想获得 10 个邻接矩阵,每个

s
一个。我想要的输出应如下所示:

print(A.shape)
>> (6, 6, 10)

请指教

python networkx
1个回答
0
投票

如评论中所示,您可能希望生成单独的有向图而不是多重有向图。

也就是说,如果你想基于

sample_id
导出多个邻接矩阵,你可以导出为 pandas DataFrame,然后用
pivot_table
重塑形状并用
groupby
拆分数组:

nodes = list(G.nodes)

df = (nx.to_pandas_edgelist(G)
        .pivot_table(index=['sample_id', 'source'],
                     columns='target', values='weight')
        .reindex(columns=nodes)
     )

matrices = {k: g.droplevel(0).reindex(nodes).to_numpy()
            for k, g in df.groupby('sample_id')}

然后:

matrices[6]

array([[       nan, 0.42310646,        nan,        nan,        nan,
               nan],
       [       nan,        nan, 0.73799541,        nan,        nan,
               nan],
       [       nan,        nan,        nan, 0.32295891,        nan,
               nan],
       [       nan,        nan,        nan,        nan, 0.31226122,
               nan],
       [       nan,        nan,        nan,        nan,        nan,
        0.25045537],
       [       nan,        nan,        nan,        nan,        nan,
               nan]])
© www.soinside.com 2019 - 2024. All rights reserved.