我有一个NetworkX问题。我用熊猫DataFrame制作了一个有向图,沿着边缘设置了一些数据。现在,我需要计算节点后代的唯一源的#,并访问edge属性。
这是我的代码,它适用于一个节点,但是我需要传递很多节点到这个节点,并得到唯一的计数。
graph = nx.from_pandas_edgelist(df, source="source", target="target",
edge_attr=["domain", "category"], create_using=nx.DiGraph)
downstream_nodes = list(nx.descendants(graph, node))
downstream_nodes.append(node)
subgraph = graph.subgraph(downstream_nodes).copy()
domain_sources = {}
for s, t, v in subgraph.edges(data=True):
if v["domain"] in domain_sources:
domain_sources[v["domain"]].append(s)
else:
domain_sources[v["domain"]] = [s]
down_count = {}
for k, v in domain_sources.items():
down_count[k] = len(list(set(v)))它可以工作,但是,同样,对于一个节点来说,时间并不是什么大事,但是我至少要在40到50个节点上提供这个例程。这是最好的方法吗?我还能做些什么来根据边缘属性进行分组并唯一地计数节点吗?
发布于 2020-01-08 20:35:49
两个可能的改进:
from collections import defaultdict
import networkx as nx
# missing part of df creation
graph = nx.from_pandas_edgelist(df, source="source", target="target",
edge_attr=["domain", "category"], create_using=nx.DiGraph)
downstream_nodes = list(nx.descendants(graph, node))
downstream_nodes.append(node)
subgraph = graph.subgraph(downstream_nodes)
domain_sources = defaultdict(set)
for s, t, v in subgraph.edges(data=True):
domain_sources[v["domain"]].add(s)
down_count = {}
for k, v in domain_sources.items():
down_count[k] = len(set(v))https://stackoverflow.com/questions/59637382
复制相似问题