【问题标题】:Pandas DataFrames to GraphPandas DataFrames to Graph
【发布时间】:2021-03-07 00:55:55
【问题描述】:
给定两个 DataFrame,一个用于节点,另一个用于边缘。如何将它们放入包含我拥有的属性列的 networkx 图中?
例子:
df_nodes
|
ID |
Label |
Attribute_W |
Attribute_X |
| 0 |
0 |
Japan |
Asia |
81 |
| 1 |
1 |
Mexico |
America |
52 |
| 2 |
2 |
Ireland |
Europe |
353 |
df_Edges
|
Target |
Source |
Attribute_Y |
Attribute_Z |
| 0 |
0 |
1 |
10 |
1 |
| 1 |
0 |
2 |
15 |
2 |
| 2 |
1 |
2 |
20 |
3 |
我尝试使用 G = nx.from_pandas_edgelist 但它返回属性错误。而且我不确定如何在图表的构造中添加属性。
我希望输出一个 graphml 文件 nx.write_graphml(G, "My_File.graphml")
谢谢。
【问题讨论】:
标签:
python
pandas
networkx
【解决方案1】:
我也看不到如何通过 from_pandas_edgelist 包含节点属性。但是,您可以在几行代码中使用 nx.add_edges_from 和 nx.add_nodes_from 来实现您想要的。
G = nx.Graph()
node_label_attr = "Label"
for index,row in df_nodes.iterrows():
as_dict = row.to_dict()
label = as_dict[node_label_attr]
del as_dict[node_label_attr]
G.add_nodes_from([(label, as_dict)])
for index,row in df_Edges.iterrows():
as_dict = row.to_dict()
source = as_dict["Source"]
target = as_dict["Target"]
del as_dict["Source"]
del as_dict["Target"]
G.add_edges_from([(source,target,as_dict)])
您遍历数据帧的行并将它们转换为 nx.add_nodes_from 和 nx.add_edges_from 可以理解的字典。