简体   繁体   中英

Can we add multiple weights to a singe edge in a simple graph generated using Python NetworkX package?

In the following documentation for the network.Graph.edges: https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.edges.html

it is illustrated how we add weight to an edge:

G = nx.path_graph(3)  
G.add_edge(2, 3, weight=5)

My question is, can we add multiple weights to the same edge in a simple (not multi) graph?

For example, I want to create a simple graph depicting the contact network of employees working in an organization. A node in my network denotes an employee while creating the network, I want to draw an edge between two employees when they meet each other, but I want to assign multiple weights based on the time they spent together in performing different categories of work together, eg say node A and node B spends 5 hours in working on a project, 2 hours in a meeting, 1 hour in lunch.

Thanks for your reply in advance.

You can add as many edge attributes as you want. Example:

>>> G.add_edge(2, 3, lunch_time=1, project_time=5, meeting_time=2)
>>> G.edges[2,3]
{'weight': 5, 'lunch_time': 1, 'project_time': 5, 'meeting_time': 2}
>>> G.edges[2,3]['lunch_time']
1

The answer is no but that's not that bad. G.add_edge(2, 3, weight=5) is a method that gives an instruction update keys 2 and 3 in dictionary G._adj which is an attribute used internally in nx.Graph() class.

After an update it looks this way:

G._adj = {2: {3: {'weight': 5}}, 3: {2: {'weight': 5}}}

As much as you can't have same keys in dictionary, assignment of different values to the same weight attribute is not possible.

In order to store hours spent, you can use dictionaries, tuples, lists or any other datatypes that would be good for you, for example:

G.add_edges(2, 3, weight = {'project': 5, 'meeting': 2, 'lunch':1})

They are single values too, it should just be (at least, normally) iterable ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM