[Tutor] Help with two .shp file and python coding

Tariq Khasiri tariqkhasiri at gmail.com
Mon Mar 27 22:58:31 EDT 2023


Hello everyone,

For a particular project, I need to collect the distance data from each US
county to the nearest intersection of interstate highway.

These are the publicly provided dataset where anyone has access to the
county shp files of usa and roads shp files.

this one for county polygons
https://public.opendatasoft.com/explore/dataset/us-county-boundaries/information/

this one for primary roads

https://catalog.data.gov/dataset/tiger-line-shapefile-2016-nation-u-s-primary-roads-national-shapefile/resource/d983eeef-21d9-4367-9d42-27a131ee72b8

```
import geopandas as gpd
from shapely.geometry import Point

# Load shapefiles
counties = gpd.read_file('path/to/counties.shp')
interstates = gpd.read_file('path/to/interstates.shp')

# Perform spatial join to find nearest interstate for each county
joined = gpd.sjoin_nearest(counties, interstates)

# Calculate distance between each county and its nearest interstate
def calculate_distance(row):
    county_point = row.geometry.x, row.geometry.y
    interstate_point = row.geometry_nearest.x, row.geometry_nearest.y
    return Point(county_point).distance(Point(interstate_point))

joined['distance'] = joined.apply(calculate_distance, axis=1)

# Save results to file
joined.to_file('path/to/output.shp')
```

do you think I can execute my goal successfully with the code snippet above
??


More information about the Tutor mailing list