计算networkx中的二分图

时间:2018-05-03 15:51:39

标签: python networkx bipartite

假设以下示例性边缘列表:

source,target,weight
162600,117237,200
192084,50240,200
200854,125014,200
166729,37059,5
157279,77297,1
186788,35124,2
199103,112437,5
194523,125618,5
169139,103847,5
156565,85646,5
157159,85646,10
168455,115687,15
139567,108206,5
172702,120323,5
175029,120590,5
167596,85646,10
202163,83381,15
163786,109135,5
183035,124200,4
154266,124200,2
187899,124200,20
190849,124200,8
169657,118867,11
157848,101997,2
143224,87832,1
140758,101009,21
197618,101009,20
175454,50240,4
150071,112472,10
199517,121453,20

如您所见,source的某些元素有一个共同的target。因此,我认为计算和可视化网络X中的二分图是有意义的。

documentation显示了如何使用手动值完成,但我想知道它如何从上面应用于边缘列表(包括权重。

如果有人能够提供使用上述数据的示例,我将非常感激,尽管输入数据可能会导致网络稀疏。

1 个答案:

答案 0 :(得分:0)

我建议在有向图中顺利运行add_weighted_edges_from()函数。这是在将输入数据按照请求放入元组列表之后。 请查看此documentation以获取更多信息

import networkx as nx
import matplotlib.pyplot as plt
%matplotlib inline

INPUT = [
    (162600,117237,200),
    (192084,50240,200),
    (200854,125014,200),
    (166729,37059,5),
    (157279,77297,1),
    (186788,35124,2),
    (199103,112437,5),
    (194523,125618,5),
    (169139,103847,5),
    (156565,85646,5),
    (157159,85646,10),
    (168455,115687,15),
    (139567,108206,5),
    (172702,120323,5),
    (175029,120590,5),
    (167596,85646,10),
    (202163,83381,15),
    (163786,109135,5),
    (183035,124200,4),
    (154266,124200,2),
    (187899,124200,20),
    (190849,124200,8),
    (169657,118867,11),
    (157848,101997,2),
    (143224,87832,1),
    (140758,101009,21),
    (197618,101009,20),
    (175454,50240,4),
    (150071,112472,10),
    (199517,121453,20)
]

G=nx.DiGraph()
G.add_weighted_edges_from(INPUT)

elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 22]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 21]

pos = nx.spring_layout(G, k=1)

plt.figure(figsize=(15,10))

# nodes
nx.draw_networkx_nodes(G, pos, node_size=700)

# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge,
                       width=6)
nx.draw_networkx_edges(G, pos, edgelist=esmall,
                       width=1, alpha=0.5, edge_color='b', style='dashed')

# labels
nx.draw_networkx_labels(G, pos, font_size=12, font_family='sans-serif')

plt.axis('off')
plt.show()

这应该是输出

enter image description here