python - 将 pandas 数据框转换为定向 networkx 多图

标签 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'])

&得到

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() 但它不方便

最佳答案

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

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

关于python - 将 pandas 数据框转换为定向 networkx 多图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53834084/

相关文章:

python - Joblib Parallel 不会终止进程

python - 访问 Pandas 中索引对象的类别代码

java - 将 HashMap 用于节点和图数据结构

"default"条件语句的 Pythonic 方式?

python - CNN 使用具有显着尺寸差异的图像

python - 使用 pandas 的 TimeGrouper() 以 1 秒为间隔查找列数

python - 使用 pandas 拆分几列

django - Django 中的无环图

python - 使用邻接表表示最小生成树

python - 如何获取列表中的第一个非空项