是否可以使用Networkx和Python获取基于节点属性的度中心值?
Is it possible to obtain the degree centrality values based on the node attributes using Networkx and Python?
我是 Networkx 的新手,我想知道是否有任何方法可以输出以下内容:
Let's say I have a network whose nodes are people's names and their attributes are their gender(M,F).
When obtaining the degree centrality
degree_cent = nx.degree_centrality(g)
Instead of having something like this:
[('Anna', 1.0),('Ben',0.6), ...
Is it possible to have something like this:
[('Anna', M:0.4, F:0.6),('Ben', M:0.3, F:0.3),... where I can distinguish the number of nodes with M and F attributes that are connected to my nodes of interest?
Thank you.
需要自己写度函数:
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}
我是 Networkx 的新手,我想知道是否有任何方法可以输出以下内容:
Let's say I have a network whose nodes are people's names and their attributes are their gender(M,F). When obtaining the degree centrality degree_cent = nx.degree_centrality(g)
Instead of having something like this:
[('Anna', 1.0),('Ben',0.6), ...
Is it possible to have something like this:
[('Anna', M:0.4, F:0.6),('Ben', M:0.3, F:0.3),... where I can distinguish the number of nodes with M and F attributes that are connected to my nodes of interest?
Thank you.
需要自己写度函数:
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}