Search code examples
python-3.xgraph-theorygeopandasconnected-components

Python 3: Geopandas dataframe with CRS coordinates into Graph to find connected components and other graph properties?


I have a geopandas dataframe where I find to use some graph theory package to find graph properties such as connected components.

How can I find graph-theoretic properties conveniently with Geopandas dataframe?


Solution

  • You can use pysal to generate spatial weights matrix (which is internally graph) - http://pysal.org/notebooks/lib/libpysal/weights.html. All weights classes have from_dataframe option.

    Spatial weights can be further exported to networkx Graph object for further graph-based analysis.

    import libpysal
    import geopandas
    
    df = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
    
    W = libpysal.weights.Queen.from_dataframe(df)  # generate spatial weights
    
    G = W.to_networkx() # get networkx.Graph
    

    Notice that for some of the things (like components), you can use weights directly - see attributes in docs https://pysal.org/libpysal/generated/libpysal.weights.W.html#libpysal.weights.W.