为每个节点迭代变量 | Python 图中的节点连接

发布于 2024-12-09 03:25:56 字数 877 浏览 1 评论 0原文

我想找到图中节点 1 和其余节点之间的节点连接性。输入文本文件格式如下:

1 2 1
1 35 1
8 37 1

依此类推,共167行。第一列代表源节点,第二列代表目标节点,最后一列代表边的权重。

我正在尝试从输入文件中读取源节点、目标节点并在它们之间形成边缘。然后我需要查明它是否是一个连接的网络(只有图的一个组件,没有子组件)。 代码

from numpy import*
import networkx as nx
G=nx.empty_graph()

for row in file('out40.txt'):
    row = row.split()
    src = row[0]
    dest = row[1]
    #print src
    G.add_edge(src, dest)
    print src, dest

for i in range(2, 41):
    if nx.bidirectional_dijkstra(G, 1, i): print "path exists from 1 to ", i

这是使用 Works 手动添加边缘的

G.add_edge(1, 2)

,但很乏味,不适合像我这样的大型输入文件。当我手动添加边缘时,if 循环条件有效,但对上述代码抛出以下错误:

in neighbors_iter
raise NetworkXError("The node %s is not in the graph."%(n,))
networkx.exception.NetworkXError: The node 2 is not in the graph.

任何帮助将不胜感激!

I would like to find node connectivity between node 1 and rest of the nodes in a graph. The input text file format is as follows:

1 2 1
1 35 1
8 37 1

and so on for 167 lines. First column represents source node, second column represents destination node while the last column represents weight of the edge.

I'm trying to read the source, destination nodes from input file and forming an edge between them. I need to then find out if it is a connected network (only one component of graph and no sub-components). Here is the code

from numpy import*
import networkx as nx
G=nx.empty_graph()

for row in file('out40.txt'):
    row = row.split()
    src = row[0]
    dest = row[1]
    #print src
    G.add_edge(src, dest)
    print src, dest

for i in range(2, 41):
    if nx.bidirectional_dijkstra(G, 1, i): print "path exists from 1 to ", i

manually adding the edges using

G.add_edge(1, 2)

works but is tedious and not suitable for large input files such as mine. The if loop condition works when I add edges manually but throws the following error for the above code:

in neighbors_iter
raise NetworkXError("The node %s is not in the graph."%(n,))
networkx.exception.NetworkXError: The node 2 is not in the graph.

Any help will be much appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

铃予 2024-12-16 03:25:56

在您的代码中,您将添加节点 "1""2" 等(因为从文件中读取将会为您提供字符串,除非您显式转换它们) 。

但是,您随后尝试引用节点 12。我猜 networkx 不认为 2 == "2"

尝试将其更改

G.add_edge(src, dest)

为:

G.add_edge(int(src), int(dest))

In your code, you're adding nodes "1" and "2" et cetera (since reading from a file is going to give you strings unless you explicitly convert them).

However, you're then trying to refer to nodes 1 and 2. I'm guessing that networkx does not think that 2 == "2".

Try changing this...

G.add_edge(src, dest)

to this:

G.add_edge(int(src), int(dest))
赢得她心 2024-12-16 03:25:56

不确定这是否适合您,但您是否知道networkx 对多种图形文本格式的内置支持

边缘列表格式似乎非常适合您的情况。具体来说,以下方法将读取您的输入文件,而不需要自定义代码:

G = nx.read_weighted_edgelist(filename)

如果您想删除权重(因为您不需要它们),您可以随后执行以下操作:

for e in G.edges_iter(data=True):
    e[2].clear()                   #[2] is the 3rd element of the tuple, which 
                                   #contains the dictionary with edge attributes

Not sure if that is an option for you, but are you aware of the build-in support of networkx for multiple graph text formats?

The edge list format seems to apply pretty well to your case. Specifically, the following method will read your input files without the need for custom code:

G = nx.read_weighted_edgelist(filename)

If you want to remove the weights (because you don't need them), you could subsequently do the following:

for e in G.edges_iter(data=True):
    e[2].clear()                   #[2] is the 3rd element of the tuple, which 
                                   #contains the dictionary with edge attributes
审判长 2024-12-16 03:25:56

来自 Networkx 文档

for row in file('out40.txt'):
    row = row.split()
    src = row[0]
    dest = row[1]
    G.add_nodes_from([src, dest])
    #print src
    G.add_edge(src, dest)
    print src, dest

错误消息显示图表 < code>G 没有您要在其间创建边的节点。

From Networkx documentation:

for row in file('out40.txt'):
    row = row.split()
    src = row[0]
    dest = row[1]
    G.add_nodes_from([src, dest])
    #print src
    G.add_edge(src, dest)
    print src, dest

The error message says the the graph G doesn't have the nodes you are looking to create an edge in between.

别想她 2024-12-16 03:25:56

您还可以使用“is_connected()”使这变得更简单。例如

$ cat disconnected.edgelist
1 2 1
2 3 1
4 5 1
$ cat connected.edgelist 
1 2 1
2 3 1
3 4 1
$ ipython

In [1]: import networkx as nx

In [2]: print(nx.is_connected(nx.read_weighted_edgelist('disconnected.edgelist')))
False

In [3]: print(nx.is_connected(nx.read_weighted_edgelist('connected.edgelist')))
True

You can also use "is_connected()" to make this a little simpler. e.g.

$ cat disconnected.edgelist
1 2 1
2 3 1
4 5 1
$ cat connected.edgelist 
1 2 1
2 3 1
3 4 1
$ ipython

In [1]: import networkx as nx

In [2]: print(nx.is_connected(nx.read_weighted_edgelist('disconnected.edgelist')))
False

In [3]: print(nx.is_connected(nx.read_weighted_edgelist('connected.edgelist')))
True
朕就是辣么酷 2024-12-16 03:25:56

另一种选择是将文件作为 pandas 数据帧加载,然后使用 iterrows 进行迭代:

import pandas as pd
import networkx as nx

cols = ["src", "des", "wei"]
df = pd.read_csv('out40.txt', sep=" ", header=None, names=cols)
G = nx.empty_graph()

for index, row in df.iterrows():
    G.add_edge(row["src"], row["des"])

Another option is to load the file as a pandas dataframe and then use iterrows to iterate:

import pandas as pd
import networkx as nx

cols = ["src", "des", "wei"]
df = pd.read_csv('out40.txt', sep=" ", header=None, names=cols)
G = nx.empty_graph()

for index, row in df.iterrows():
    G.add_edge(row["src"], row["des"])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文