基于另一列连接节点列

Connect column of nodes based on another column

我需要建立一个网络,其中的节点是网站,并且应该根据分配的分数进行分组。如果网站是新的,那么它将有一个标签 1,否则为 0。

数据示例:

url          score             label
web1           5                 1
web2           10                1
web3           5                 0
web4           2                 0
...

我试过用networkx建网。为了根据分数将网络组合在一起,我只是将分数用作公共节点(但可能会有更好的方式来表示它)。 我想根据标签列为网页着色,但我不知道该怎么做。 我的代码是:

import networkx as nx

G = nx.from_pandas_edgelist(df, 'url', 'score')


nodes = G.nodes()
plt.figure(figsize=(40,50)) 
pos = nx.draw(G, with_labels=True, 
              nodelist=nodes,
              node_size=1000) 

希望大家多多指教

如果您也想将 score 作为节点包括在内,分区图可能是个好主意。您可以像以前一样使用 nx.from_pandas_edgelist 创建图形,然后将节点属性更新为:

B = nx.from_pandas_edgelist(df, source='url', target='score')

node_view = B.nodes(data=True)
for partition_nodes, partition in zip((df.url, df.score), (0,1)):
    for node in partition_nodes.to_numpy():
        node_view[node]['bipartite'] = partition

现在我们有了每个节点的分区属性:

B.nodes(data=True)
NodeDataView({'web1': {'bipartite': 0}, 5: {'bipartite': 1}, 'web2': 
{'bipartite': 0}, 10: {'bipartite': 1}, 'web3': {'bipartite': 0}, 
'web4': {'bipartite': 0}, 2: {'bipartite': 1}})

图表可以用分区布局表示:

part1_nodes = [node for node, attr in B.nodes(data=True) if attr['bipartite']==0]
fig = plt.figure(figsize=(12,8))
plt.box(False)
nx.draw_networkx(
    B,
    pos = nx.drawing.layout.bipartite_layout(B, part1_nodes),
    node_color=[]
    node_size=800)