python - 是否可以使用 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 属性的节点数感兴趣的节点?
谢谢你。
解决方案
您需要编写自己的度函数:
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}
推荐阅读
- c# - 在存储库中使用时 DbContext 何时被垃圾收集或处置?
- gpu - 如何在 H2O AutoML 中禁用 GPU
- css - 将绝对位置定位在屏幕顶部之外
- javascript - React:更改 url 而不重新渲染;使用window.history?
- ios - 将下周(7 天)从当前 var(Int)添加到 swiftui 中的 10 位 unix 时间戳
- sql-server - 每个 SQL Server 连接会增加多少 CPU 开销?我应该使用一个连接还是多个连接?
- flutter - 如果使用自定义颜色,“setState”在导航页面中不起作用
- python - Kivy 数据包 err0r
- node.js - VSCode 一直给我同样的错误:*“npm ERR!在 discord-bot@1.0.0 启动脚本失败。”*
- java - 有没有办法将 AuthenticationException 抛出到 AuthenticationEntryPoint 中?