Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas dataframe to directed networkx multigraph

I have a dataframe as below.

import pandas as pd
import networkx as nx

df = pd.DataFrame({'source': ('a','a','a', 'b', 'c', 'd'),'target': ('b','b','c', 'a', 'd', 'a'), 'weight': (1,2,3,4,5,6) })

I want to convert it to directed networkx multigraph. I do

G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight'])

& get

G.edges(data = True)
[('d', 'a', {'weight': 6}),
 ('d', 'c', {'weight': 5}),
 ('c', 'a', {'weight': 3}),
 ('a', 'b', {'weight': 4})]
G.is_directed(), G.is_multigraph()
(False, False)

But i want to get

[('d', 'a', {'weight': 6}),
 ('c', 'd', {'weight': 5}),
 ('a', 'c', {'weight': 3}),
 ('b', 'a', {'weight': 4}),
('a', 'b', {'weight': 2}),
('a', 'b', {'weight': 4})]

I have found no parameter for directed & multigraph in this manual. I can save df as txt and use nx.read_edgelist() but it's not convinient

like image 405
Edward Avatar asked Dec 18 '18 13:12

Edward


2 Answers

As you want a directed multi-graph, you could do:

import pandas as pd
import networkx as nx

df = pd.DataFrame(
    {'source': ('a', 'a', 'a', 'b', 'c', 'd'),
     'target': ('b', 'b', 'c', 'a', 'd', 'a'),
     'weight': (1, 2, 3, 4, 5, 6)})


M = nx.from_pandas_edgelist(df, 'source', 'target', ['weight'], create_using=nx.MultiDiGraph())
print(M.is_directed(), M.is_multigraph())

print(M.edges(data=True))

Output

True True
[('a', 'c', {'weight': 3}), ('a', 'b', {'weight': 1}), ('a', 'b', {'weight': 2}), ('c', 'd', {'weight': 5}), ('b', 'a', {'weight': 4}), ('d', 'a', {'weight': 6})]
like image 165
Dani Mesejo Avatar answered Oct 19 '22 03:10

Dani Mesejo


Use the create_using parameter :

create_using (NetworkX graph) – Use the specified graph for result. The default is Graph()

G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight'], create_using=nx.DiGraph())
like image 6
Corentin Limier Avatar answered Oct 19 '22 04:10

Corentin Limier