将Pandas数据框转换为有向Networkx Multigraph

时间:2018-12-18 13:26:44

标签: python pandas graph networkx

我有一个如下数据框。

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

我想将其转换为有向的networkx多重图形。我会

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)

但是我想得到

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

在此manual中,没有找到有向和多重图形的参数。 我可以将df保存为txt并使用nx.read_edgelist(),但这并不方便

2 个答案:

答案 0 :(得分:4)

使用create_using参数:

  

create_using(NetworkX图形)–将指定的图形用于结果。默认值为Graph()

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

答案 1 :(得分:2)

要获得有向多图,您可以执行以下操作:

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

输出

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})]