Chapter 2 — Practice Spatial Points Lines Polygons cont.
Spatial Points, Lines and Polygons in Python
5 min readJan 10
--
Objectives for this part:
- Create new spatial objects (points, lines, polygons)
- Assign the correct projection or CRS
- Create points from a table or csv of lat and lon
Creating GeoDataFrame Geometries
# Import necessary modules first
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point, LineString, Polygon
import fiona
import matplotlib.pyplot as plt
plt.style.use('bmh') # better for plotting geometries vs general plots.
First, create an empty GeoDataFrame
and create a new column called geometry that will contain our Shapely objects:
# Create an empty geopandas GeoDataFrame
newdata = gpd.GeoDataFrame()
print(newdata)
Empty GeoDataFrame
Columns: []
Index: []
GeoDataFrame Components
- data: a pandas.DataFrame, dictionary, or empty list [] containing an desired attribute data. Use [] if no data is
- crs: Coordinate Reference System of the geometry objects. Can be anything accepted by
pyproj.CRS.from_user_input()
, such as an authority string (eg “EPSG:4326”) or a WKT string. - geometry: Column name in a DataFrame to use as geometry or Shapely point, line, or polygon object.
Create Points from list of coordinates
Single point:
# Coordinates of the GW department of geography in Decimal Degrees
coordinate = [-77.04639494419096, 38.89934963421794]
# Create a Shapely point from a coordinate pair
point_coord = Point(coordinate)
# create a dataframe with needed attributes and required geometry column
df = {'GWU': ['Dept Geography'], 'geometry': [point_coord]}
# Convert shapely object to a geodataframe
point = gpd.GeoDataFrame(df, geometry='geometry', crs ="EPSG:4326")
# Let's see what we have
point.plot()
Multiple points:
# list of attributes and coordinates
df = pd.DataFrame(
{'City': ['Buenos Aires', 'Brasilia', 'Santiago'…