python - 将 pandas 数据帧转换为有向 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})]
我在本手册中没有找到directed & multigraph 的参数。我可以保存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})]
推荐阅读
- apache - 为什么这个 .htaccess 重写代码没有正确重定向?
- graph - 如何知道节点/特征贡献?
- c++ - 为什么此代码段有效?如何取消引用 nullptr?
- css - 在 CSS 中更改页面的颜色配置文件
- verilog - 我什么时候应该在 SystemVerilog 中使用关键字“assign”?
- kubernetes - 在没有云提供商负载均衡器的情况下,将 kubernetes 集群暴露给“世界”
- python - Pygame collidepoint()无法正常工作
- c# - Nuget 问题:接口一直引用旧版本
- javascript - NavLink:悬停和活动时的 CSS 动画
- java - 类符号 FirebaseInstanceIdService [FCM android]