使用Pandas数据框将边缘权重分配给networkx图 [英] Assign edge weights to a networkx graph using pandas dataframe

查看:291
本文介绍了使用Pandas数据框将边缘权重分配给networkx图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am contructing a networkx graph in python 3. I am using a pandas dataframe to supply the edges and nodes to the graph. Here is what I have done :

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

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

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

What I want is that the "callDuration" column of the pandas dataframe act as the weight of the edges for the networkx graph and the thickness of the edges also change accordingly.

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

I also want to get the 'n' maximum weighted edges.

推荐答案

让我们尝试:

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)

输出:

这篇关于使用Pandas数据框将边缘权重分配给networkx图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆