简体   繁体   中英

MultiDirectional Graph in python using networkX

Problem is relatively simple and I am not able to find any pointers for the same. I have a csv with following values :

 Source Destination value
    a         b     0.7
    b         c     0.58
    c         d     0.4
    a         d     0.52
    b         d     0.66
    d         b     0.30
    a         c     0.33

I want to do a graph analysis with python and I found networkx to be the suitable option. I used the following code to achieve the same.

import networkx as nx
import pandas as pd

df = pd.read_csv('values.csv')

G = nx.from_pandas_edgelist(df, source='Source', target='Destination', edge_attr='value',)   

G.nodes()

G.edges()


nx.draw_networkx(G, with_labels=True)

Since the values in the csv have b -> d and d-> b it would be a multidirectional graph but when I try to output the result, I am not getting these values.

G.nodes()
NodeView(('a', 'b', 'c', 'd'))

G.edges()
EdgeView([('a', 'b'), ('a', 'd'), ('a', 'c'), ('b', 'c'), ('b', 'd'), ('c', 'd')])

Output

I want to understand why I am not able to obtain the edge for d -> b in the edge response.

I found nx.MultiDiGraph on the documentation but I am not sure how to use the same.

Thanks

In addition to @KPLauritzen's answer, I used the following to get the MultiDirectional weighted graph :

Graphtype = nx.MultiDiGraph()

G = nx.from_pandas_edgelist(df, source='Source', target='Destination', edge_attr='value',create_using=Graphtype)   

You should just use the DiGraph when creating the graph.

G = nx.from_pandas_edgelist(df, source='Source', target='Destination', edge_attr='value', create_using=nx.DiGraph)
print(G.edges())
# OutEdgeView([('a', 'b'), ('a', 'd'), ('a', 'c'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('d', 'b')])

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