Remove unconnected polylines from a shapefile ArcPy

I would solve the problem with NetworkX. It’s an Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It supports import and export of shapefile format. Install NetworkX in your ArcGIS Python environment: pip install networkx

The following code should give you one possibility to solve your problem: First, add an unique ID Field (e.g. "MY_FID") to your polyline shapefile. Than you can build a python dictionary, where the key is the ID field and the value is the number of the polyline group.

import arcpy
import networkx as nx

polyline_shapefile = r"D:\Test\polylines.shp"

# Add id and group fields
arcpy.AddField_management(polyline_shapefile, "GROUP", "LONG")
arcpy.AddField_management(polyline_shapefile, "MY_FID", "LONG")
oid_fieldname = arcpy.Describe(polyline_shapefile).OIDFieldName
arcpy.CalculateField_management(polyline_shapefile, "MY_FID", "!{oid}!".format(oid=oid_fieldname), "PYTHON_9.3")

polyline_group_fid_dict = {}
polyline_graph = nx.read_shp(polyline_shapefile, simplify=False).to_undirected()

# loop all connected components (polyline groups) of the polyline network graph 
for component_number, polyline_group in enumerate(nx.connected_component_subgraphs(polyline_graph)):
    for polyline in polyline_group.edges():
        fid = polyline_group.get_edge_data(polyline[0], polyline[1])["MY_FID"]
        polyline_group_fid_dict[fid] = component_number

# add the polyline group id to the "GROUP" field.
with arcpy.da.UpdateCursor(polyline_shapefile, ["MY_FID", "GROUP"]) as cursor:
    for row in cursor:
        row[1] = polyline_group_fid_dict[row[0]]
        cursor.updateRow(row)

Now you can count the lines per group or dissolve the polylines by the "GROUP" field and calculate the length of the polyline groups.

Tags:

Line

Arcpy