使用pandas数据帧将边缘权重分配给networkx图

问题描述 投票:0回答:2

我正在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'个最大加权边。

python-3.x pandas graph networkx weighted-graph
2个回答
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


0
投票

不同意所说的话。在不同指标的计算中,考虑到每个边缘的权重,如pagerank或betweeness中心性,如果存储为边缘属性,则不会考虑您的权重。使用图表。

Add_edges(source, target, weight, *attrs)

© www.soinside.com 2019 - 2024. All rights reserved.