Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Text File of Graph data using NetworkX

Tags:

graph

networkx

I'm very new to networkX. So having problem in very basic things.

I've network data in the text file in following format:

InNode  OutNode

 N1       N5
 N2       N4
 N3       N6
 N2       N2
 N4       N7

My questions are the following:

1) How to read the data using networkX, so that I can get the nodes and edges between the graph?

2) How to calculate the self-edge of the network (N2, N2)?

I tried the following code. But it's not giving me the right answer.

import matplotlib
import networkx as net
import urllib
import csv


g = net.Graph()

f1 = csv.reader(open("data.txt","rb"))

for row in f1: 
    g.add_nodes_from(row)

len(g)

g.number_of_nodes()
like image 728
Beta Avatar asked Dec 12 '16 18:12

Beta


1 Answers

Please find the solution. This might help someone like me:

# Reading the file. "DiGraph" is telling to reading the data with node-node. "nodetype" will identify whether the node is number or string or any other type.


g = nx.read_edgelist("data.txt",create_using=nx.DiGraph(), nodetype = int)

# check if the data has been read properly or not.

nx.info(g)

# count the number of nodes

g.number_of_nodes()

# number of self-nodes

g.selfloop_edges()
like image 177
Beta Avatar answered Oct 11 '22 05:10

Beta