Reputation: 31040
Just wondering if there is convenient networkx
function that returns a list of edges connected to a given node (or nodes) (e.g. my_node_name
) in a graph (e.g. G
).
I can do it this way:
edlist=[]
for ed in G.edges():
if 'my_node_name' in ed:
edlist.append(ed)
but expect there might be a better way?
Upvotes: 73
Views: 96374
Reputation: 936
For directed multi-graphs, I found the following workaround for out-edges:
import networkx as nx
a = nx.MultiDiGraph()
a.add_edge("a", "b", 0)
a.add_edge("a", "b", 1)
a.add_edge("b", "c", 0)
a.add_edge("b", "c", 1)
# This is too much:
print(a.edges)
# OutMultiEdgeView([('a', 'b', 0), ('a', 'b', 1), ('b', 'c', 0), ('b', 'c', 1)])
# This is insufficient:
print(a.in_edges("b"))
# InMultiEdgeDataView([('a', 'b'), ('a', 'b')])
# This is just right
print(a["a"])
# AdjacencyView({'b': {0: {}, 1: {}}})
print(a["a"]["b"])
# AtlasView({0: {}, 1: {}})
For in-edges, you should probably first use a.in_edges(node)
and then a[source][node]
to get the edge types.
Once you get all the triplets t = (source, sink, type)
, you can access the edge by calling a.edges[t]
.
Upvotes: 1
Reputation: 23166
You can use the method edges
on a node for an un-directed graph:
G.edges(['my_node_name'])
or the function edges
networkx.edges(G, ['my_node_name'])
But for directed graphs the above method will only give the out-edges; there you need to call and combine both in_edges()
and out_edges()
.
Upvotes: 18
Reputation: 23827
If the graph is undirected, you can use
G.edges(node)
In networkx 2.x this is an EdgeDataView
object. In networkx 1.x this is a list - if you want a generator in 1.x rather than getting the whole list, G.edges_iter(node)
works (this no longer exists in 2.x).
If the graph is directed the command above will not give the in-edges. Use
G.in_edges(node)
G.out_edges(node)
These are views in 2.x. In 1.x these are lists and there are generator options: G.in_edges_iter(node)
and G.out_edges_iter(node)
Upvotes: 116