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
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})]
Use the create_using
parameter :
create_using
(NetworkX graph) – Use the specified graph for result. The default isGraph()
G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight'], create_using=nx.DiGraph())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With