我有一个包含这个节点的csv文件,每个节点的关联坐标如下:
node x y
A1 67.8 15.53
A2 108.74 15.53
B1 67.8 25.33
B2 108.74 25.33
C1 67.8 30.22
C2 108.74 30.22
D1 67.8 37.99
D2 108.74 37.99
E1 67.8 43.84
对于每个节点,我有另一个带边的文件,它表示每个连接节点之间的距离,如下所示:
node1 node2 distance
A1 A2 40.90
A1 B1 9.8
A2 B2 9.8
B1 A1 9.8
...
那么,我该怎么做才能将节点及其相应的边添加到同一个图中呢?
我试过这个,但它不起作用:
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import numpy
nodes = pd.read_csv('nodes.csv')
print nodes
G = nx.Graph()
for row in nodes.iterrows():
G.add_node(row[1][0], x=row[1][2],y=row[1][3])
edgelist = pd.read_csv('edges.csv')
print edgelist
for i, elrow in edgelist.iterrows():
G.add_edge(elrow.node1,elrow.node2,weight=elrow.distance)
G.nodes(data=True)
nx.draw(G)
plt.show()
我是Python的新手,我需要将其作为硕士论文代码的一部分。我使用的是python 3.6,但我也安装了2.7版本。你能帮我做这个吗?
答案 0 :(得分:1)
Networkx有一些utility functions可以让您的生活更轻松一些。
您可以使用nx.from_pandas_dataframe
直接从edges
DataFrame:
edges = pd.read_csv('edges.csv', sep='\s+')
G = nx.from_pandas_dataframe(edges, 'node1', 'node2', ['distance'])
然后您可以通过将nodes
DataFrame转换为dicts列表来添加节点属性,然后将其加载到图表G
中G.add_nodes_from(data)
:
nodes = pd.read_csv('nodes.csv', sep='\s+')
data = nodes.set_index('node').to_dict('index').items()
G.add_nodes_from(data)
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
edges = pd.read_csv('edges.csv', sep='\s+')
G = nx.from_pandas_dataframe(edges, 'node1', 'node2', ['distance'])
nodes = pd.read_csv('nodes.csv', sep='\s+')
data = nodes.set_index('node').to_dict('index').items()
G.add_nodes_from(data)
print(G.nodes(data=True))
print(G.edges(data=True))
打印(对于G.nodes(data=True)
):
NodeDataView({'D1': {'y': 37.990000000000002, 'x': 67.799999999999997}, 'A1': {'y': 15.529999999999999, 'x': 67.799999999999997}, 'C2': {'y': 30.219999999999999, 'x': 108.73999999999999}, 'B2': {'y': 25.329999999999998, 'x': 108.73999999999999}, 'D2': {'y': 37.990000000000002, 'x': 108.73999999999999}, 'C1': {'y': 30.219999999999999, 'x': 67.799999999999997}, 'A2': {'y': 15.529999999999999, 'x': 108.73999999999999}, 'E1': {'y': 43.840000000000003, 'x': 67.799999999999997}, 'B1': {'y': 25.329999999999998, 'x': 67.799999999999997}})
和(对于G.edges(data=True)
):
EdgeDataView([('A1', 'A2', {'distance': 40.9}), ('A1', 'B1', {'distance': 9.8}), ('B2', 'A2', {'distance': 9.8})])
答案 1 :(得分:0)
from_pandas_dataframe
不适用于networkx v2。
我在这里找到了正确的方法名称:AttributeError: module 'networkx' has no attribute 'from_pandas_dataframe'
对我来说有效的是:
G = nx.from_pandas_edgelist(edges, 'src', 'tgt', edge_attr=True)
之后,我可以使用其余的已接受答案:
data = nodedf.set_index('id').to_dict('index').items()
G.add_nodes_from(data)