[GIS] Using GeoPandas to create a graph

geopandaspython

I have a shapefile with some polygons and I'd like to create a graph that assigns vertices to polygons and creates edges between vertices if the corresponding polygons share a border. Since I'm using networkx, a Python graph library, I was thinking of using GeoPandas to convert from the shapefile to a nx graph. Does anyone have any idea how to do this?

(networkx has a built-in read_shp method, but I don't think that's what I want; I'm pretty sure (but not confident) that that translates points to vertices and lines to edges, not polygons and borders.)

Best Answer

You could use pysal to create a contiguity matrix. This can be done from a data frame using pysal.weights.Rook.from_dataframe(args), or direct from a shapefile. You could then use this to add nodes (these are the keys in both dictionaries dictionary) and edges (a list of tuples of each key paired with each neighbour from it's value list. Something like:

import networkx as nx
import pysal

#build contiguity matrix - uses rook contiguity - queen is available
path_to_shp = r'come/path/to/file.shp'
my_keys = 'name_of_id_for_your_features'
contig_matrix = pysal.weights.Rook.from_shapefile(path_to_shp,idVariable = my_keys)

#build list of edges - this will create edges going both ways from connected nodes, so you might need to remove duplicates
nodes = contig_matrix.weights.keys() # to get dict of keys, alternatively use contig_matrix.id2i.keys()
edges = [(node,neighbour) for node in nodes for neighbour in contig_matrix[node]]
my_graph = nx.Graph(edges)