7

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

2
  • 1
    what version of networkx do you have? I have version 2.1 and G=nx.from_pandas_edgelist(df, 'source', 'target', ['weight']) works correctly Commented Dec 18, 2018 at 13:32
  • 1
    There is a create_using argument which takes different graph types. I haven't tried this personally, but perhaps some luck with that? Commented Dec 18, 2018 at 13:34

2 Answers 2

9

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})]
Sign up to request clarification or add additional context in comments.

Comments

6

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.