Visualizing Geospatial Data in Python
Mary van Valkenburg
Data Science Program Manager, Nashville Software School
# centroid of first polygon
print(districts.geometry.centroid[0])
Point(-87.256 36.193)
GeoSeries.centroid
# print the first 5 rows of school districts
print(school_districts.head())
first_name last_name district geometry
Sharon Gentry 1 (POLYGON ((-86.771 36.383...
Jill Speering 3 (POLYGON ((-86.753 36.404...
Jo Ann Brannon 2 (POLYGON ((-86.766 36.083...
Anna Shepherd 4 (POLYGON ((-86.580 36.209...
Amy Frogge 9 (POLYGON ((-86.972 36.208...
# create 'center` column from the centroid school_districts['center'] = school_districts.geometry.centroid
# create GeoDataFrame with districts and centers part = ['district', 'center'] school_district_centers = school_districts[part] school_district_centers.head(3)
district center
1 POINT (-86.86086595994405 36.2628221811899)
3 POINT (-86.72361421487962 36.28515517790142)
2 POINT (-86.70156420691957 36.03021153030475)
GeoSeries.distance(other)
- returns minimum distance to other
# distance from red_pt to centroid
cen = districts.geometry.centroid[0]
print(red_pt.distance(other = cen))
24.273
district_one = school_districts.loc[school_districts.district == '1']
district_one.head()
first_name last_name district center geometry
Sharon Gentry 1 POINT (-86.860 36.262) (POLYGON ((-86.771...
schools.head(3)
name lat lng
AZ Kelley Elem 36.021 -86.658
Alex Green Elem 36.252 -86.832
Amqui Elem 36.27 -86.703
# create geometry in schools
schools['geometry']=gpd.points_from_xy(schools.lng, schools.lat)
#construct schools GeoDataFrame
school_geo=gpd.GeoDataFrame(schools,crs = district_one.crs,
geometry = schools.geometry)
# spatial join schools within dist 1
schools_in_dist1 = gpd.sjoin(schools_geo, district_one, predicate = 'within')
schools_in_dist1.shape
(30, 8)
# import pprint to format dictionary output
import pprint
distances = {}
for row in schools_in_dist1.iterrows():
vals = row[1]
key = vals['name']
ctr = vals['center']
distances[key] = vals['geometry'].distance(ctr)
pprint.pprint(distances)
{'Alex Green Elementary': 0.030287172719682773,
'Bellshire Elementary': 0.0988045140909651,
'Brick Church College Prep': 0.08961013862715599,
'Buena Vista Elementary': 0.10570511270825833,
'Cockrill Elementary': 0.1077685612196105....
Visualizing Geospatial Data in Python