Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign edge weights to a networkx graph using pandas dataframe

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')

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.

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

like image 394
Anand Nautiyal Avatar asked Sep 19 '18 07:09

Anand Nautiyal


2 Answers

Let's try:

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)

Output:

enter image description here

like image 82
Scott Boston Avatar answered Oct 20 '22 14:10

Scott Boston


Do not agree with what has been said. In the calcul of different metrics that takes into account the weight of each edges like the pagerank or the betweeness centrality your weight would not be taking into account if is store as an edge attributes. Use graph.

Add_edges(source, target, weight, *attrs)

like image 24
joseph Assouline Avatar answered Oct 20 '22 14:10

joseph Assouline