简体   繁体   中英

Scipy construct a network graph from text file

I have the following data that represents a graph in a text file:

     a,b,1
     a,c,2
     b,c,1
     etc..

I need to build a matrix representation of this graph using SciPy. Right now, I read everything in a dictionary:

graph = { "a" : [("b",1), ("c",2)],
          "b" : [("b",1)]
        }

My question is how to move from a dictionary to an numpy array. Or if there is anyway to read directly from the text file into a numpy array using numpy.loadtxt()?

Edit

Desired format is a scipy csr_matrix representing the graph:

  a b c
a 0 1 2
b 0 0 1
c 0 0 0

if you want to convert a dict to an numpy array you can easily use:

import numpy as np
array = np.array(list(graph.items()))

i couldn't try it but i hope it can helps you

To convert a dictionary to a dataframe of the form

  a b c
a 0 1 2
b 0 0 1
c 0 0 0

you can give a properly formed dictionary to the constructor. It accepts a dictionary.

graph = { "a" : [0, 0, 0],
          "b" : [1, 0, 0],
          "c" : [2, 1, 0]
        }

import pandas as pd
my_df = pd.DataFrame(graph)

Also, check here for an example of how to convert an edge list to an adjacency matrix:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM