gpt4 book ai didi

python - 如何在 Networkx 图中生成组件 ID?

转载 作者:行者123 更新时间:2023-12-04 14:54:55 24 4
gpt4 key购买 nike

我有一个使用 Networkx 包生成的大型图形网络。

enter image description here

这里我添加了一个示例

import networkx as nx
import pandas as pd

G = nx.path_graph(4)
nx.add_path(G, [10, 11, 12])

我正在尝试创建一个包含节点、度数、组件 ID、组件的 dataframe

创建学位使用

degrees = list(nx.degree(G))

data = pd.DataFrame([list(d) for d in degrees], columns=['Node', 'degree']).sort_values('degree', ascending=False)

使用提取的组件

Gcc = sorted(nx.connected_components(G), key=len, reverse=True)

Gcc
[{0, 1, 2, 3}, {10, 11, 12}]

并且不确定如何在数据中创建 Component IDcomponents

要求的输出:

  Node  degree  ComponentID  Components
1 1 2 1 {0, 1, 2, 3}
2 2 2 1 {0, 1, 2, 3}
5 11 2 2 {10, 11, 12}
0 0 1 1 {0, 1, 2, 3}
3 3 1 1 {0, 1, 2, 3}
4 10 1 2 {10, 11, 12}
6 12 1 2 {10, 11, 12}

如何生成组件id并将它们添加到节点和度数中?

最佳答案

通过枚举连接的组件列表,创建 NodeComponentIdComponent 三元组,然后从这些三元组创建一个新的数据帧和 merge 它与 Node

上的给定数据帧
df = pd.DataFrame([(n, i, c) for i,c in enumerate(Gcc, 1) for n in c], 
columns=['Node', 'ComponentID', 'Components'])

data = data.merge(df, on='Node')

或者,您可以使用 map 而不是 merge 来单独创建 ComponentIDComponents

d = dict(enumerate(Gcc, 1))
data['ComponentID'] = data['Node'].map({n:i for i,c in d.items() for n in c})
data['Components'] = data['ComponentID'].map(d)

print(data)

Node degree ComponentID Components
1 1 2 1 {0, 1, 2, 3}
2 2 2 1 {0, 1, 2, 3}
5 11 2 2 {10, 11, 12}
0 0 1 1 {0, 1, 2, 3}
3 3 1 1 {0, 1, 2, 3}
4 10 1 2 {10, 11, 12}
6 12 1 2 {10, 11, 12}

关于python - 如何在 Networkx 图中生成组件 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68235334/

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