2

I have a dataset that contains a user and each friend they have. The format is similar to the below where there is a user_id field and friend_id field containing the corresponding IDs of each friend.

user_id | friend_id
   A          B
   A          C
   B          A
   B          G

I'm aiming to get an undirected graph showing an edge between each user and every friend they have like below.

A - B - G
|
C

I'm having difficulty finding out how to link pandas to networkx or graphviz and other resources that expand on creating a social graph from tabular data.

2
  • Why do you need to do it directly from pandas? you can iterate over the records and create the relevant nodes and edges. Commented Jul 6, 2018 at 12:04
  • shhh @black hasn't finished their test yet. Commented Aug 13, 2018 at 22:44

1 Answer 1

2

As an example here is a way to show an undirected network graph using networkx, pandas, and matplotlib.

Code:

import matplotlib.pyplot as plt
import networkx as nx

# store pairs to a list of tuples
tuples = [tuple(x) for x in df.values]

# set up a graph and show it
G = nx.DiGraph()
G.add_edges_from(tuples)
nx.draw_networkx(G)
plt.xticks([], [])
plt.yticks([], [])
plt.show()

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

was able to clean up your answer for my use case. Had to look through the networkX docs a bit more and get what I wanted. Thanks for your help in getting the starter code together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.