Week 3: Geospatial Data Analysis and GeoPandas

Sep 20, 2021

Housekeeping

  • Homework #1 due today
  • Homework #2 due a week from Wednesday (9/29)
  • Choose a dataset to visualize and explore
    • OpenDataPhilly or one your choosing
    • Email me if you want to analyze one that's not on OpenDataPhilly

Update your local environment

  • Small update to course's Python environment
  • A recent update for one of the packages we'll use contained a bug that impact this week's slides
  • Update the environment on your laptop using these instructions on course website

Agenda for Week #3

  • Vector data and introduction to GeoPandas
  • Spatial relationships and joins
  • Visualization for geospatial data
  • Demo: 311 requests by neighborhood in Philadelphia
  • Exercise: Property assessments by neighborhood

Now, on to geospatial analysis...

In [2]:
# Let's setup the imports we'll need first
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd

Vector Data

A couple of terminology notes

  • A feature refers to both the geometry and attributes of specific piece of vector data
  • A feature collection is a list, or collection, of features

Both terms are very common in Python geospatial software.

Common formats for vector datasets

A shapefile

Actually several files with the same common prefix

Mandatory files:

  • .shp: the file containing the geometries
  • .shx: the file that indexes the geometry
  • .dbf: tabular data format storing the attributes for each geometry

And many optional files for documentation, projection information, etc.

Let's take a look at an example shapefile:

We'll use the %ls command to list out all of the files in an example shapefile in the data/ folder

In [2]:
%ls "data/ne_110m_admin_0_countries/"
ne_110m_admin_0_countries.cpg  ne_110m_admin_0_countries.shp
ne_110m_admin_0_countries.dbf  ne_110m_admin_0_countries.shx
ne_110m_admin_0_countries.prj

The GeoJSON file

  • Stores simple features in a JSON format
  • Arose due to the prevalence of the JSON format, especially on the web

Additional GeoJSON resources and tools:

  • GitHub lets you view GeoJSON files natively
  • http://geojson.io provides interactive creation and viewing of small GeoJSON files

GitHub example from the data/ directory: Philadelphia ZIP Codes

Working with vector data in Python: GeoPandas

geopandas provides a simple, intuitive for the main types of geospatial vector file formats

EgXiUhLWAAQcYCM.jpeg

Example: Let's load a shape file of countries in the world...

Source: Natural Earth Data

In [74]:
import geopandas as gpd

We can use the read_file() function to read shapefiles and GeoJSON files.

In [75]:
# Read the shape file, giving the name of the directory
countries = gpd.read_file("./data/ne_110m_admin_0_countries")
In [76]:
countries.head()
Out[76]:
iso_a3 name continent pop_est gdp_md_est geometry
0 AFG Afghanistan Asia 34124811.0 64080.0 POLYGON ((61.21082 35.65007, 62.23065 35.27066...
1 AGO Angola Africa 29310273.0 189000.0 MULTIPOLYGON (((23.90415 -11.72228, 24.07991 -...
2 ALB Albania Europe 3047987.0 33900.0 POLYGON ((21.02004 40.84273, 20.99999 40.58000...
3 ARE United Arab Emirates Asia 6072475.0 667200.0 POLYGON ((51.57952 24.24550, 51.75744 24.29407...
4 ARG Argentina South America 44293293.0 879400.0 MULTIPOLYGON (((-66.95992 -54.89681, -67.56244...
In [77]:
type(countries) 
Out[77]:
geopandas.geodataframe.GeoDataFrame

What's a GeoDataFrame?

Just like a DataFrame but with a geometry column

In [78]:
# Print out the first 10 entires of the "geometry" column
countries['geometry'].head(n=10)
Out[78]:
0    POLYGON ((61.211 35.650, 62.231 35.271, 62.985...
1    MULTIPOLYGON (((23.904 -11.722, 24.080 -12.191...
2    POLYGON ((21.020 40.843, 21.000 40.580, 20.675...
3    POLYGON ((51.580 24.245, 51.757 24.294, 51.794...
4    MULTIPOLYGON (((-66.960 -54.897, -67.562 -54.8...
5    POLYGON ((43.583 41.092, 44.972 41.248, 45.179...
6    MULTIPOLYGON (((-59.572 -80.040, -59.866 -80.5...
7    POLYGON ((68.935 -48.625, 69.580 -48.940, 70.5...
8    MULTIPOLYGON (((145.398 -40.793, 146.364 -41.1...
9    POLYGON ((16.980 48.123, 16.904 47.715, 16.341...
Name: geometry, dtype: geometry

We can still leverage the power of pandas...

Calculate the total world population:

In [79]:
countries['pop_est'].sum()/1e9 # In billions
Out[79]:
7.383089462

Calculate the total population on each continent:

In [80]:
grouped = countries.groupby('continent')
grouped 
Out[80]:
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7fb8da962a00>
REMEMBER:
Remember: the groupby() does not return a DataFrame — you need to call sum(), mean(), etc, or apply() a function.
In [82]:
# Sum population on each continent
pop_by_continent = grouped['pop_est'].sum()

# Sort values
pop_by_continent.sort_values(ascending=False, inplace=True)

# Output sorted values from cell
pop_by_continent/1e9
Out[82]:
continent
Asia                       4.389145e+00
Africa                     1.219176e+00
Europe                     7.463985e-01
North America              5.730421e-01
South America              4.185407e-01
Oceania                    3.678284e-02
Antarctica                 4.050000e-06
Seven seas (open ocean)    1.400000e-07
Name: pop_est, dtype: float64

Filter the data frame based on a boolean selection:

In [90]:
# Is the country name USA?
is_USA = countries['name']=='United States of America'

# Get the row with USA
USA = countries.loc[is_USA]

USA
Out[90]:
iso_a3 name continent pop_est gdp_md_est geometry
168 USA United States of America North America 326625791.0 18560000.0 MULTIPOLYGON (((-122.84000 49.00000, -120.0000...

An aside: the squeeze() function

It does just one it sounds like: if you have a DataFrame with only one row, it will "squeeze" the row dimension by removing it, returning just a Series object:

In [94]:
# Squeeze
USA = USA.squeeze()

# Print out the type
print("The type of USA is: ", type(USA))

# Output
USA
The type of USA is:  <class 'pandas.core.series.Series'>
Out[94]:
iso_a3                                                      USA
name                                   United States of America
continent                                         North America
pop_est                                             326625791.0
gdp_md_est                                           18560000.0
geometry      (POLYGON ((-122.84 49.00000000000014, -120 49....
Name: 168, dtype: object

The simple features (Lines, Points, Polygons) are implemented by the shapely library

In [95]:
type(USA.geometry)
Out[95]:
shapely.geometry.multipolygon.MultiPolygon

Jupyter notebook renders shapely geometries automatically:

In [96]:
# a mini USA
USA.geometry 
Out[96]:

How does geopandas handle coordinate systems and map projections?

Coordinate Reference Systems

A coordinate reference system (CRS) relates the position of a geometry object on the spherical earth to its two-dimensional coordinates.

A GeoDataFrame or GeoSeries has a .crs attribute which specifies the coordinate reference system.

In [97]:
countries.crs
Out[97]:
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
  • EPSG 4326 is known as WGS 84 where x and y are longitude and latitude.
  • It is is the default coordinate system for GPS systems.
  • It's also known as Plate Carrée

How to plot all of the geometries at once?

Use the plot() function to get a quick and dirty plot of all of the geometry features.

Note: the plot() returns the current maplotlib axes, allowing you to format the chart after plotting.

In [99]:
# Create a figure and axes
fig, ax = plt.subplots(figsize=(10, 6))

# Plot the countries on our axes
ax = countries.plot(ax=ax, facecolor="none", edgecolor="black")

# Add a title
ax.set_title("Equirectangular Projection")
Out[99]:
Text(0.5, 1.0, 'Equirectangular Projection')

What's going on under the hood?

matplotlib and cartopy are combined to make geo-aware plots

In [101]:
import cartopy.crs as ccrs 
In [18]:
# Initialize the EPSG:4326 CRS object
wgs84 = ccrs.PlateCarree()

# Create a geo-aware axes using the "projetion" keyword
fig, ax = plt.subplots(figsize=(10, 6), subplot_kw={"projection": wgs84})

# Print out the type of the axes for info purposes
print("The type of the axes is: ", type(ax))

# Add the geometry shapes
a x.add_geometries(countries["geometry"], crs=wgs84, facecolor="none", edgecolor="black")

# Add a title
ax.set_title("Equirectangular Projection");
The type of the axes is:  <class 'cartopy.mpl.geoaxes.GeoAxesSubplot'>

See the Geopandas documentation for more examples: Plotting with CartoPy and GeoPandas

Can we convert to other geometries?

Use the to_crs() function. The most well-known projections can be specified by their EPSG code.

Geopandas documentation on re-projecting: Managing Projections

Let's convert to the Mercator projection

EPSG code: 3395

In [102]:
# Remove Antartica, as the Mercator projection 
# cannot deal with the poles
no_antartica = countries.loc[(countries['name'] != "Antarctica")]  
In [103]:
# Two ways to specify the EPSG code
countries_mercator = no_antartica.to_crs(epsg=3395)

# Alternatively:
#countries_mercator = no_antartica.to_crs("EPSG:3395")
In [104]:
countries_mercator.head() 
Out[104]:
iso_a3 name continent pop_est gdp_md_est geometry
0 AFG Afghanistan Asia 34124811.0 64080.0 POLYGON ((6813956.990 4227673.562, 6927484.435...
1 AGO Angola Africa 29310273.0 189000.0 MULTIPOLYGON (((2660998.216 -1305442.810, 2680...
2 ALB Albania Europe 3047987.0 33900.0 POLYGON ((2339940.185 4961221.199, 2337708.178...
3 ARE United Arab Emirates Asia 6072475.0 667200.0 POLYGON ((5741805.754 2765811.385, 5761611.935...
4 ARG Argentina South America 44293293.0 879400.0 MULTIPOLYGON (((-7453944.198 -7306880.704, -75...

Note: the magnitude of the values in the geometry column changed! A quick and easy way to tell if the re-projection worked properly!

Now let's plot it

The easy way...with geopandas built-in plot() function

In [106]:
# Initialize the figure and axes
fig, ax = plt.subplots(figsize=(10, 6))

# Use built-in plot() of the GeoDataFrame
ax = countries_mercator.plot(ax=ax, 
                             facecolor="none", 
                             edgecolor="black")

# Add a title
ax.set_title("Mercator Projection");

The harder way...

With cartopy and matplotlib

In [107]:
# Initialize the CRS object
crs = ccrs.epsg(3395) # or crs = ccrs.Mercator()

# Create a geo-aware axes using the "projetion" keyword
fig, ax = plt.subplots(figsize=(10, 6), 
                       subplot_kw={"projection": crs})

# Add the geometry shapes
ax.add_geometries(countries_mercator['geometry'], 
                  crs=crs, facecolor='none', edgecolor='black')

# Add a title
ax.set_title('Mercator Projection');

When to use the 'harder' way?

When you need more customizable, advanced plots.

Nearly anything that matplotlib can do can be plotted on a cartopy GeoAxes. Plotting directly with matplotlib allows you to take full advantage of matplotlib's functionality.

So which CRS is best?

Let's load the city limits for Philadelphia

We'll use the provided City_Limits shape file in the data/ folder

In [108]:
city_limits = gpd.read_file('./data/City_Limits')

city_limits
Out[108]:
OBJECTID Shape__Are Shape__Len geometry
0 1 0.038911 1.259687 POLYGON ((-75.01497 40.13793, -75.01456 40.137...

What's the CRS?

Use the .crs attribute to find out!

In [109]:
city_limits.crs
Out[109]:
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [110]:
# Create our figure and axes
fig, ax = plt.subplots(figsize=(5, 5))

# Plot
city_limits.plot(ax=ax, facecolor="none", edgecolor="black")

# Format
ax.set_title("Equirectangular")
ax.set_axis_off() # This will remove the axes completely
ax.set_aspect("equal") # This forces an equal aspect ratio

This is not what Philadelphia looks like..

Let's try EPSG=3857 instead:

In [111]:
# Create the figure
fig, ax = plt.subplots(figsize=(5, 5))

# Convert to EPSG:3857
city_limits_3857 = city_limits.to_crs(epsg=3857)

# Plot and format
city_limits_3857.plot(ax=ax, facecolor="none", edgecolor="black")

ax.set_title("Web Mercator")
ax.set_axis_off()
ax.set_aspect("equal");

Important: the equirectangular CRS (EPSG=4326) is often used by default and will make cities appear wider and flatter than they really are

Saving GeoDataFrames

Use the to_file() function and specify the driver.

In [112]:
# ESRI shape file
city_limits_3857.to_file("./data/city_limits_3857", 
                         driver='ESRI Shapefile') 
In [113]:
# GeoJSON is also an option
city_limits_3857.to_file("./data/city_limits_3857.geojson", 
                         driver='GeoJSON')

How about as a CSV file?

Yes, but reading requires more work...

In [114]:
# save a csv file
city_limits_3857.to_csv("./data/city_limits_3857.csv", index=False)
In [115]:
df = pd.read_csv("./data/city_limits_3857.csv")
df.head()
Out[115]:
OBJECTID Shape__Are Shape__Len geometry
0 1 0.038911 1.259687 POLYGON ((-8350627.97509646 4886006.88680784, ...

Looks similar...

But, the "geometry" column is just stored as a string...it's not a shapely Polygon

In [119]:
type(df.geometry) 
Out[119]:
pandas.core.series.Series

Use shapely to parse the string version of the polygons

In [121]:
from shapely import wkt

# wkt.loads will convert from string to Polygon object
df['geometry'] = df['geometry'].apply(wkt.loads)
In [123]:
df.geometry.iloc[0] 
Out[123]:

Converting from a DataFrame to a GeoDataFrame

We can initialize the GeoDataFrame directly from a DataFrame but we need to specify two things:

  1. The name of the "geometry" column
  2. The CRS of the "geometry" column

In this case, the geometry column was saved in Web Mercator EPSG=3857

In [124]:
# Make specifying the name of the geometry column and CRS
gdf= gpd.GeoDataFrame(df, geometry='geometry', crs="EPSG:3857")

# Now plot
fig, ax = plt.subplots(figsize=(5,5))
ax = gdf.plot(ax=ax, facecolor='none', edgecolor='black')
ax.set_axis_off()
ax.set_aspect("equal")

Let's convert back to 4326 and plot

The tilt should be a bit more obvious now...

In [128]:
ax = (
    gdf.to_crs(epsg=4326)
      .plot(facecolor='none', edgecolor='black')
)
 
ax.set_axis_off()
ax.set_aspect("equal")

Note

  • I didn't use plt.subplots() here to create a figure/axes – I let geopandas automatically make one
  • I've chained together the to_crs() and .plot() functions in one line
  • The .plot() function returns the axes object that geopandas used to plot — this lets you customizes the axes after plotting

So, when should you use GeoPandas?

  • For exploratory data analysis and visualization, including in Jupyter notebooks
  • Pre-processing data to be fed into a desktop GIS program
  • For compact, readable, and reproducible code
  • If you’re comfortable with Pandas and/or R data frames.

When it may not be the best tool:

  • For polished multilayer map creation — one option is to use a desktop GIS like QGIS.
  • If you need very high performance — geopandas can be slow compared to other GIS software.

Spatial Relationships and Joins

In [129]:
# Load some cities data
cities = gpd.read_file("./data/ne_110m_populated_places")

All of these operations are available as functions of a GeoDataFrame.

A quick example

What country is New York in?

Spoiler: the USA

In [133]:
# Select the Point representing New York City
new_york = cities.loc[cities['name'] == 'New York', 'geometry'].squeeze()
new_york
Out[133]:
In [134]:
type(new_york)
Out[134]:
shapely.geometry.point.Point
In [135]:
countries.contains(new_york)
Out[135]:
0      False
1      False
2      False
3      False
4      False
       ...  
172    False
173    False
174    False
175    False
176    False
Length: 177, dtype: bool
In [136]:
# Find the country that contains New York
countries.loc[countries.contains(new_york)]
Out[136]:
iso_a3 name continent pop_est gdp_md_est geometry
168 USA United States of America North America 326625791.0 18560000.0 MULTIPOLYGON (((-122.84000 49.00000, -120.0000...
In [138]:
# Get the geometry column of the country containing NYC
USA = countries.loc[countries.contains(new_york)].squeeze().geometry
USA
Out[138]:

Note

The .loc[] function can take the index selector as the first argument, and the name of a column as a second argument (separated by a comma)

In [43]:
type(USA)
Out[43]:
shapely.geometry.multipolygon.MultiPolygon
In [139]:
# Is New York within the USA?
new_york.within(USA)
Out[139]:
True

Reference

The different functions for checking spatial relationships:

  • equals
  • contains
  • crosses
  • disjoint
  • intersects
  • overlaps
  • touches
  • within
  • covers

See the shapely documentation for an overview of these methods.

The spatial join

SPATIAL JOIN = merging attributes from two geometry layers based on their spatial relationship

Different parts of this operations:

  • The GeoDataFrame to which we want add information
  • The GeoDataFrame that contains the information we want to add
  • The spatial relationship we want to use to match both datasets (intersects, contains, within)
  • The type of join: left or inner join

In this case, we want to join the cities dataframe, containing Point geometries, with the information of the countries dataframe, containing Polygon geometries.

To match cities with countries, we'll use the within spatial relationship.

The geopandas.sjoin() function performs this operation:

In [140]:
joined = gpd.sjoin(cities, countries, op='within', how='left') 
In [141]:
joined.head() 
Out[141]:
name_left geometry index_right iso_a3 name_right continent pop_est gdp_md_est
0 Vatican City POINT (12.45339 41.90328) 79.0 ITA Italy Europe 62137802.0 2221000.0
1 San Marino POINT (12.44177 43.93610) 79.0 ITA Italy Europe 62137802.0 2221000.0
2 Vaduz POINT (9.51667 47.13372) 9.0 AUT Austria Europe 8754413.0 416600.0
3 Lobamba POINT (31.20000 -26.46667) 152.0 SWZ Swaziland Africa 1467152.0 11060.0
4 Luxembourg POINT (6.13000 49.61166) 97.0 LUX Luxembourg Europe 594130.0 58740.0
In [150]:
cities_in_italy = joined.loc[joined['name_right'] == 'Italy']
cities_in_italy
Out[150]:
name_left geometry index_right iso_a3 name_right continent pop_est gdp_md_est
0 Vatican City POINT (12.45339 41.90328) 79.0 ITA Italy Europe 62137802.0 2221000.0
1 San Marino POINT (12.44177 43.93610) 79.0 ITA Italy Europe 62137802.0 2221000.0
226 Rome POINT (12.48131 41.89790) 79.0 ITA Italy Europe 62137802.0 2221000.0
In [152]:
# Extract Italy
italy = countries.loc[countries['name']=='Italy']

# Plot
fig, ax = plt.subplots(figsize=(8,8))
italy.plot(ax=ax, facecolor='none', edgecolor='black')
ax.set_axis_off()
ax.set_aspect("equal")

# Plot the first city in the joined data frame (Vatican City)
# Use the same axes by passing in the ax=ax keyword
ax = cities_in_italy.plot(ax=ax, color='red')  

Spatial overlay operation

We can also perform the join() operation on the geometries rather than just combining attributes.

The overlay() function combines geometries, e.g. by taking the intersection of the geometries.

In [153]:
africa = countries.loc[countries['continent'] == 'Africa'] 
In [154]:
## What crs?
africa.crs
Out[154]:
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [155]:
# Let's transform to a CRS that uses meters 
# instead of degrees (EPSG=3857)
africa = africa.to_crs(epsg=3857)

africa.crs
Out[155]:
<Projected CRS: EPSG:3857>
Name: WGS 84 / Pseudo-Mercator
Axis Info [cartesian]:
- X[east]: Easting (metre)
- Y[north]: Northing (metre)
Area of Use:
- name: World between 85.06°S and 85.06°N.
- bounds: (-180.0, -85.06, 180.0, 85.06)
Coordinate Operation:
- name: Popular Visualisation Pseudo-Mercator
- method: Popular Visualisation Pseudo Mercator
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [156]:
fig, ax = plt.subplots(figsize=(8,8))

africa.plot(ax=ax, facecolor='#b9f2b1')

ax.set_axis_off()
ax.set_aspect("equal") 
In [157]:
# Important CRS needs to match!
cities = cities.to_crs(epsg=3857)
In [53]:
# Create a copy of the GeoDataFrame
buffered_cities = cities.copy()

# Add a buffer region of 250 km around all cities
buffered_cities['geometry'] = buffered_cities.buffer(250e3)

Plot the difference of the two geometries

In [158]:
fig, ax = plt.subplots(figsize=(8, 8))

# Calculate the difference of the geometry sets
diff = gpd.overlay(africa, buffered_cities, how='difference')

# Plot
diff.plot(facecolor="#b9f2b1", ax=ax)
ax.set_axis_off()
ax.set_aspect("equal")
In [160]:
# Data attributes are the same as the first data frame (africa) 
# with an updated geometry column
diff.head()
Out[160]:
iso_a3 name continent pop_est gdp_md_est geometry
1 AGO Angola Africa 29310273.0 189000.0 MULTIPOLYGON (((2673464.087 -1449571.330, 2441...
13 BEN Benin Africa 11038805.0 24310.0 POLYGON ((100138.898 1231805.081, 138422.412 1...
14 BFA Burkina Faso Africa 20107509.0 32990.0 MULTIPOLYGON (((100138.898 1231805.081, 26368....
25 BWA Botswana Africa 2214858.0 35900.0 POLYGON ((3065120.801 -2659823.621, 3061281.52...
26 CAF Central African Rep. Africa 5625118.0 3206.0 POLYGON ((1792937.514 836963.765, 1813457.017 ...

Plot the intersection of the two geometries

In [164]:
fig, ax = plt.subplots(figsize=(8, 8))

# The intersection of the geometry sets
intersection = gpd.overlay(africa, buffered_cities, how='intersection')

# Plot
intersection.plot(ax=ax, facecolor="#b9f2b1")
ax.set_axis_off()
ax.set_aspect("equal")

Recap:

  • Spatial join: merge attributes from one data frame to another based on the spatial relationship
  • Spatial overlay: creating new geometries based on spatial operation between both data frames (and not combining attributes of both data frames)

Putting it all together: 311 requests in 2020

Load 311 requests in Philadelphia from the data/ directory.

Source: OpenDataPhilly

In [166]:
# Load the data from a CSV file into a pandas DataFrame
requests = pd.read_csv('./data/public_cases_fc_2020.csv.tar.gz')
/Users/nhand/opt/miniconda3/envs/musa-550-fall-2021/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3441: DtypeWarning: Columns (12) have mixed types.Specify dtype option on import or set low_memory=False.
  exec(code_obj, self.user_global_ns, self.user_ns)
In [167]:
print("number of requests = ", len(requests))
number of requests =  727746
In [59]:
requests.head()
Out[59]:
objectid service_request_id status status_notes service_name service_code agency_responsible service_notice requested_datetime updated_datetime expected_datetime address zipcode media_url lat lon
0 7890359 13127945 Closed Question Answered Information Request SR-IR01 Police Department NaN 2020-02-05 11:00:11 2020-02-05 11:00:23 2020-02-05 11:30:20 NaN NaN NaN NaN NaN
1 9551814 13788036 Closed Question Answered Information Request SR-IR01 State/Federal Government Offices NaN 2020-11-24 11:34:27 2020-11-24 11:34:32 2020-11-24 12:00:24 NaN NaN NaN NaN NaN
2 8138665 13251716 Closed NaN Information Request SR-IR01 License & Inspections NaN 2020-03-26 11:40:36 2020-03-26 11:40:47 2020-03-26 12:00:21 NaN NaN NaN NaN NaN
3 8433329 13376073 Closed NaN Information Request SR-IR01 License & Inspections NaN 2020-05-22 12:00:10 2020-05-22 12:00:39 2020-05-22 12:30:22 NaN NaN NaN NaN NaN
4 8433331 13376078 Closed NaN Information Request SR-IR01 Streets Department NaN 2020-05-22 12:00:44 2020-05-22 12:00:53 2020-05-22 12:30:22 NaN NaN NaN NaN NaN

First, convert to a GeoDataFrame

Remove the requests missing lat/lon coordinates

In [168]:
requests = requests.dropna(subset=['lat', 'lon']) 

Create Point objects for each lat and lon combination.

We can use the helper utility function: geopandas.points_from_xy()

In [169]:
requests['Coordinates'] = gpd.points_from_xy(requests['lon'], requests['lat'])
In [170]:
requests['Coordinates'].head()
Out[170]:
13    POINT (-75.16257 40.04816)
18    POINT (-75.18500 40.03733)
21    POINT (-75.20887 40.02665)
24    POINT (-75.10652 40.03439)
25    POINT (-75.16350 39.93616)
Name: Coordinates, dtype: geometry

Now, convert to a GeoDataFrame.

Important

  • Don't forget to set the CRS manually!
  • The CRS you specify when creating a GeoDataFrame should tell geopandas what the coordinate system the input data is in.
  • Usually you will be reading lat/lng coordinates, and will need to specify the crs as EPSG code 4326
  • You should specify the crs as a string using the syntax: ESPG:4326

Since we're only using a few EPSG codes in this course, you can usually tell what the CRS is by looking at the values in the Point() objects.

Philadelphia has a latitude of about 40 deg and longitude of about -75 deg.

Our data must be in the usual lat/lng EPSG=4326.

Screen%20Shot%202020-09-12%20at%204.15.11%20PM.png

In [172]:
requests = gpd.GeoDataFrame(requests, 
                            geometry="Coordinates", 
                            crs="EPSG:4326")

More next time...

That's it!

  • We'll continue with geopandas and geospatial data viz next time
  • See you on Wednesday!
In [ ]: