Search code examples
pythongraphnodesnetworkxedges

How to read nodes and edges from txt files ? (or .edges and .nodes files) NetworkX


I'm struggling with making a NetworkX Graph. I have two txt files (converted from .edges and .nodes files) that look like this:


nodes.txt:

id,name,new_id

402449106435352,Josh Marks,386

368969274888,Blue Ribbon Restaurants,473

765596333518863,Pat Neely,1

136870209668885,La Griglia,542

840078802741859,Jose Garces,189

1189829367698904,Zac Kara,454

edges.txt:

0,276

0,58

0,132

0,603

0,398

0,555

1,265

I can't find a way to add edges and nodes from those files to a networkx graph. I'm either able to add only edges or add only nodes, and I'm pretty sure I'm doing something wrong. I'm new to this and I have very little knowledge of it, so I'm appreciating all the help I get.

This is what I have so far.

df_edges = pd.read_csv('food_edges.txt', sep = ',', header = None)
df_nodes = pd.read_csv('food_nodes.txt', sep = ',', header = None, names = ['id', 'name', 'new_id'])

# Try 1:
G = nx.Graph()

G.add_nodes_from(df_nodes)
G.add_edges_from(df_edges)

'''
Error : 
Traceback (most recent call last):
  File "food_net.py", line 22, in <module>
    G.add_edges_from(df_edges)
  File "C:\Python38\lib\site-packages\networkx\classes\graph.py", line 923, in add_edges_from
    ne = len(e)
TypeError: object of type 'int' has no len()
''' 

# Try 2: adding edges , but don't know how to add nodes then
g = nx.read_weighted_edgelist('fb-pages-food/fb-pages-food.edges', delimiter = ',')



Solution

  • Soo I figured that .edges is actually the only file I need for my graph, and .nodes file (the second file) is just used as a 'codebook', so I can see which food is, or change ID with the name of the food.