python - 查找网络图中的所有对

标签 python pandas dataframe graph-theory shortest-path

我正在解决一个问题。我有一个 pandas DataFrame,其中包含 Source、Target 和 Freq 列。

假设我对节点 1 感兴趣。可以通过以下方式链接节点 1。

Source Target
5 1
3 5
2 3
6 2

当 1 是目标时 5 是源,当 5 是目标并且链接继续时 3 是源。我本质上是在尝试创建一个网络图,它将是 6-2-3-5-1

有没有什么方法可以通过编程找到最终会在我选择的目标中结束的所有源-目标组合?

编辑:进行了编辑以提供更多说明。

最佳答案

Is there any way to programmatically find the all source-target combinations

是的,这被称为 Shortest path problem ,给定一个图 G,该图由节点/顶点 V 连接,由边 E 连接,找到源节点和目标节点之间的最短路径。您指定的是一个边列表,其中每个边将某个节点 v(i) 连接到另一个节点 v(j)

有几种算法可以实现解决方案。您可以使用类似 NetworkX 的库所以你不必自己实现算法。例如,

# let's create the data frame as per your example
import pandas as pd
df = pd.DataFrame([
        (5, 1),
        (3, 5),
        (2, 3),
        (6, 2),
    ], columns=['source', 'target'])

# import networkx and build the graph
import networkx as nx
G = nx.Graph()
G.add_edges_from(df.values)

# import the shortest_paths generic algorithm
nx.shortest_path(G, source=6, target=1)
=> 
[6, 2, 3, 5, 1]

find the all source-target combinations

NetworkX 提供 many algorithms您应该与您要解决的特定用例相匹配。要找到给定源节点和目标节点的所有可能路径,

# assume we have added another edge source=6 target=1 
list(nx.all_simple_paths(G, source=6, target=1))
=> 
[[6, 1], [6, 2, 3, 5, 1]]

all source-target combinations (...) that would eventually end up in a target of my choice

我们想要找到所有可能的源节点和最终以我们选择的目标结束的路径,而不指定源节点:

# find all start/end nodes
import networkx as nx
# -- we need a directed graph
dG = nx.DiGraph()
dG.add_edges_from(df.values)
# -- find possible source nodes
source_nodes = [x for x in G.nodes_iter() if dG.out_degree(x) >= 1]
# -- for every source node find the shortest path to target
paths = [nx.shortest_path(G, source=source, target=1) for source in source_nodes]
paths
=>
[[2, 3, 5, 1], [3, 5, 1], [5, 1], [6, 2, 3, 5, 1]]

关于python - 查找网络图中的所有对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53093669/

相关文章:

python - 使用 win32com 进行复制粘贴时出错(Glade GTK Python)

python - 删除所有观测值具有相同值的列是否会影响我的模型?

python - Dataframe 有一列是字典列表,我需要将它们解析为新的列

python - 如何将 numpy 数组相互映射?

Python uwsgi w/virtualenv --no-site-packages -- import site = AttributeError {'userbase' }

python - python 中 3D 可视化的现代方法 : discuss mayavi

python - 如何删除数据框中的异构元素?

python - 根据 .sum() 总计过滤 Pandas 系列

R比较相应的单元格并创建一个以内容命名的新列

R有条件地将日期时间从一个数据帧匹配到第二个数据帧中最近的日期时间字段