首页 > 解决方案 > 是否可以使用 Networkx 和 Python 根据节点属性获取度中心性值?

问题描述

我是 Networkx 的新手,我想知道是否有任何方法可以输出以下内容:

假设我有一个网络,其节点是人名,属性是他们的性别(M,F)。获得度中心度时 degree_cent = nx.degree_centrality(g)

而不是这样的:

[('安娜', 1.0),('本',0.6), ...

是否有可能有这样的东西:

[('Anna', M:0.4, F:0.6),('Ben', M:0.3, F:0.3),... 在这里我可以区分连接到我的具有 M 和 F 属性的节点数感兴趣的节点?

谢谢你。

标签: pythonattributesnodesnetworkx

解决方案


您需要编写自己的度函数:

import networkx as nx
import random

random.seed(42)

graph = nx.erdos_renyi_graph(20, .1)

classes = ["A", "B", "C"]

for node in graph:
    graph.nodes[node]["attribute"] = random.choice(classes)


def attribute_degree(G, node):
    degree = {}

    for neighbor in G.neighbors(node):
        attribute = G.nodes[neighbor]["attribute"]
        degree[attribute] = degree.get(attribute, 0) + 1

    return degree


print(attribute_degree(graph, 0))
# {'B': 1, 'A': 2, 'C': 1}
print(attribute_degree(graph, 1))
# {'B': 1, 'A': 1, 'C': 1}

推荐阅读