将pandas数据框转换为有向的networkx多重图形

7
我有一个如下的数据框。
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})]

在这个手册中,我没有找到有关有向和多重图的参数。

我可以将df保存为txt文件并使用nx.read_edgelist(),但这不太方便。


1
你使用的networkx版本是什么?我使用的是2.1版本,G=nx.from_pandas_edgelist(df, 'source', 'target', ['weight']) 正常工作。 - EdChum
1
有一个create_using参数,可以使用不同的图形类型。我个人没有尝试过,但或许会有些运气? - Unni
2个回答

9

如果您需要一个有向的多重图,可以这样做:

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

6

使用create_using参数:

create_using(NetworkX图)- 使用指定的图形结果。默认为Graph()

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接