Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list of edge attributes of a Networkx graph

I would like to know if there is any function to get the list of node/edge attributes of a Networkx graph

The function get_node_attributes/get_edge_attributes returns the attribute values when the attribute name is specified. But I'd like to know how to get the attribute names of a weighted graph.

like image 800
Natasha Avatar asked Aug 27 '20 06:08

Natasha


People also ask

What is edge attribute?

Examples of edge attributes are data associated with edges: most commonly edge weights, or visualization parameters. In recent igraph versions, arbitrary R objects can be assigned as graph, vertex or edge attributes.

What is Nbunch in NetworkX?

nbunch. An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph, etc.. To filter an nbunch so that only nodes actually in G appear, use G.


1 Answers

Both Graph.nodes and Graph.edges take a data parameter, which if set to True we get the node/edge attributes returned in a tuple as (n, dict[data]), where the second term is a dictionary containing all attributes. Here's an example:

G = nx.Graph()

G.add_node(2, lat=41.793780, long=3.972440)
G.add_node(4, lat=41.151363, long=54.374512)
G.add_node(5, lat=17.164215, long=13.92541)
G.add_node(6, lat=10.173651, long=30.335611)

G.add_edge(2, 4, weight=0.2, length=12)
G.add_edge(5, 6, weight=0.6, length=13)

By setting data=True as mentioned, we get:

G.nodes(data=True)
NodeDataView({2: {'lat': 41.79378, 'long': 3.97244}, 
              4: {'lat': 41.151363, 'long': 54.374512}, 
              5: {'lat': 17.164215, 'long': 13.92541}, 
              6: {'lat': 10.173651, 'long': 30.335611}})

G.edges(data=True)
EdgeDataView([(2, 4, {'weight': 0.2, 'length': 12}), 
              (5, 6, {'weight': 0.6, 'length': 13})])

If you only want a list with the attribute names of say, the edges, you could do:

from itertools import chain

set(chain.from_iterable(d.keys() for *_, d in G.edges(data=True)))
# {'length', 'weight'}

Or in the simpler case in which we have the same attributes for each edge:

list(list(G.edges(data=True))[0][-1].keys())
# ['weight', 'length']
like image 138
yatu Avatar answered Nov 13 '22 13:11

yatu