使用Pandas数据框将边缘权重分配给networkx图

时间:2018-09-19 07:26:09

标签: python-3.x pandas graph networkx weighted-graph

我正在python 3中构建networkx图。我正在使用pandas数据框为图提供边缘和节点。这是我所做的:

test = pd.read_csv("/home/Desktop/test_call1", delimiter = ';')

g_test = nx.from_pandas_edgelist(test, 'number', 'contactNumber', edge_attr='callDuration')

我想要的是,pandas数据帧的“ callDuration”列充当networkx图的边缘权重,并且边缘的厚度也相应地变化。

我也想获得'n'个最大加权边。

2 个答案:

答案 0 :(得分:1)

让我们尝试一下:

import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

df = pd.DataFrame({'number':['123','234','345'],'contactnumber':['234','345','123'],'callduration':[1,2,4]})

df

G = nx.from_pandas_edgelist(df,'number','contactnumber', edge_attr='callduration')
durations = [i['callduration'] for i in dict(G.edges).values()]
labels = [i for i in dict(G.nodes).keys()]
labels = {i:i for i in dict(G.nodes).keys()}

fig, ax = plt.subplots(figsize=(12,5))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, ax = ax, labels=True)
nx.draw_networkx_edges(G, pos, width=durations, ax=ax)
_ = nx.draw_networkx_labels(G, pos, labels, ax=ax)

输出:

enter image description here

答案 1 :(得分:0)

不同意所说的话。在考虑到每个边缘的权重(例如页面等级或中间居中性)的不同度量标准中,如果将其存储为边缘属性,则不会考虑您的权重。 使用图表。

Add_edges(source, target, weight, *attrs)