Creating NetworkX graph from a dataframe

Viewed 276

I am trying to build a network where nodes are people's name and edges are created between nodes/people that have a relationship index greater than 0.60.

The data are from pandas

Name      Relationship index
Julie        0.4
Marie        0.2
Bob          0.7 
Mark         0.85
Chris        0.43

What I have done is to get a linear representation of the table:

dat = df.set_index('Name').stack()

then try t establish connection between people having relationship index > 0.6:

dat = dat[dat['Relationship index']>0.6]

and get the edge list:

edges = dat.index.tolist()

Then I have been building the networks as bipartite graph:

G = nx.Graph(edges)
Gp = nx.bipartite.project(G, dat.set_index('Name').columns)

Gp.edges()

Unfortunately I am getting this error:

----> 2 dat = dat[dat['Relationship index']>0.6]

AttributeError: 'Series' object has no attribute 'Relationship index'

Can you please tell me what is wrong?

Expected output:

A graph where Bob and Mark are connected to each other and other people are disconnected.

1 Answers

What is not working in your code:

dat = df.set_index('Name').stack()
this line gets rid of column names, 
so you cannot access them with ['Relationship index']
anymore

For your specific problem, you can use itertools:

import itertools

matches = df[df['Relationship index']>.6]['Name'].tolist()
edges = itertools.product(matches, matches)

G = nx.Graph()
G.add_nodes_from(df['Name'])
G.add_edges_from(edges)

nx.draw_networkx(G)

enter image description here

Related