将 Pandas 数据帧转换为有向 networkx 多图

Edw*_*ard 5 python graph networkx pandas

我有一个如下的数据框。

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) })
Run Code Online (Sandbox Code Playgroud)

我想将其转换为有向 networkx multigraph。我愿意

G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight'])
Run Code Online (Sandbox Code Playgroud)

& 得到

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)
Run Code Online (Sandbox Code Playgroud)

但我想得到

[('d', 'a', {'weight': 6}),
 ('c', 'd', {'weight': 5}),
 ('a', 'c', {'weight': 3}),
 ('b', 'a', {'weight': 4}),
('a', 'b', {'weight': 2}),
('a', 'b', {'weight': 4})]
Run Code Online (Sandbox Code Playgroud)

我在本手册中没有发现有向图和多重图的参数。我可以保存df为 txt 并使用,nx.read_edgelist()但它不方便

Dan*_*ejo 6

当你想要一个有向多图时,你可以这样做:

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))
Run Code Online (Sandbox Code Playgroud)

输出

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})]
Run Code Online (Sandbox Code Playgroud)


Cor*_*ier 5

使用create_using参数:

create_using(NetworkX graph) – 使用指定的图作为结果。默认是Graph()

G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight'], create_using=nx.DiGraph())
Run Code Online (Sandbox Code Playgroud)