Skip to content Skip to sidebar Skip to footer

How To Create A Directed Networkx Graph From A Pandas Adjacency Matrix Dataframe?

I have a pandas dataframe of the the following form, df, A B C D A 0 0.5 0.5 0 B 1 0 0 0 C 0.8 0 0 0.2 D 0 0 1 0 I am trying to

Solution 1:

Try using numpy as a workaround.

G = nx.from_numpy_matrix(df.values, parallel_edges=True, 
                         create_using=nx.MultiDiGraph())

# Because we use numpy, labels need to be reset
label_mapping = {0: "A", 1: "B", 2: "C", 3: "D"}
G = nx.relabel_nodes(G, label_mapping)

G.edges(data=True)

OutMultiEdgeDataView([('A', 'B', {'weight': 0.5}), 
                      ('A', 'C', {'weight': 0.5}), 
                      ('B', 'A', {'weight': 1.0}), 
                      ('C', 'A', {'weight': 0.8}), 
                      ('C', 'D', {'weight': 0.2}), 
                      ('D', 'C', {'weight': 1.0})])

In a more general case, to get label_mapping you can use

label_mapping = {idx: val for idx, val in enumerate(df.columns)}

This seems to be a bug in networkx 2.0. They will fix it in 2.1. See this issue for more information.


Post a Comment for "How To Create A Directed Networkx Graph From A Pandas Adjacency Matrix Dataframe?"