<jupyter_start><jupyter_text>Introduction to geospatial vector data in Python<jupyter_code>%matplotlib inline

import pandas as pd
import geopandas

pd.options.display.max_rows = 10<jupyter_output><empty_output><jupyter_text>Importing geospatial data Geospatial data is often available from specific GIS file formats or data stores, like ESRI shapefiles, GeoJSON files, geopackage files, PostGIS (PostgreSQL) database, ...We can use the GeoPandas library to read many of those GIS file formats (relying on the `fiona` library under the hood, which is an interface to GDAL/OGR), using the `geopandas.read_file` function.For example, let's start by reading a shapefile with all the countries of the world (adapted from http://www.naturalearthdata.com/downloads/110m-cultural-vectors/110m-admin-0-countries/, zip file is available in the `/data` directory), and inspect the data:<jupyter_code>countries = geopandas.read_file("zip://./data/ne_110m_admin_0_countries.zip")
# or if the archive is unpacked:
# countries = geopandas.read_file("data/ne_110m_admin_0_countries/ne_110m_admin_0_countries.shp")
countries.head()
countries.plot()<jupyter_output><empty_output><jupyter_text>What can we observe:- Using `.head()` we can see the first rows of the dataset, just like we can do with Pandas.- There is a 'geometry' column and the different countries are represented as polygons- We can use the `.plot()` method to quickly get a *basic* visualization of the data  What's a GeoDataFrame?We used the GeoPandas library to read in the geospatial data, and this returned us a `GeoDataFrame`:<jupyter_code>type(countries)<jupyter_output><empty_output><jupyter_text>A GeoDataFrame contains a tabular, geospatial dataset:* It has a **'geometry' column** that holds the geometry information (or features in GeoJSON).* The other columns are the **attributes** (or properties in GeoJSON) that describe each of the geometriesSuch a `GeoDataFrame` is just like a pandas `DataFrame`, but with some additional functionality for working with geospatial data:* A `.geometry` attribute that always returns the column with the geometry information (returning a GeoSeries). The column name itself does not necessarily need to be 'geometry', but it will always be accessible as the `.geometry` attribute.* It has some extra methods for working with spatial data (area, distance, buffer, intersection, ...), which we will see in later notebooks<jupyter_code>countries.geometry
type(countries.geometry)
countries.geometry.area<jupyter_output><empty_output><jupyter_text>**It's still a DataFrame**, so we have all the pandas functionality available to use on the geospatial dataset, and to do data manipulations with the attributes and geometry information together.For example, we can calculate average population number over all countries (by accessing the 'pop_est' column, and calling the `mean` method on it):<jupyter_code>countries['pop_est'].mean()<jupyter_output><empty_output><jupyter_text>Or, we can use boolean filtering to select a subset of the dataframe based on a condition:<jupyter_code>africa = countries[countries['continent'] == 'Africa']
africa.plot()<jupyter_output><empty_output><jupyter_text>---**Exercise**: create a plot of South America <!--countries[countries['continent'] == 'South America'].plot()--> ---<jupyter_code>countries.head()<jupyter_output><empty_output><jupyter_text>---The rest of the tutorial is going to assume you already know some pandas basics, but we will try to give hints for that part for those that are not familiar.   A few resources in case you want to learn more about pandas:- Pandas docs: https://pandas.pydata.org/pandas-docs/stable/10min.html- Other tutorials: chapter from pandas in https://jakevdp.github.io/PythonDataScienceHandbook/, https://github.com/jorisvandenbossche/pandas-tutorial, https://github.com/TomAugspurger/pandas-head-to-tail, ... REMEMBER:   A `GeoDataFrame` allows to perform typical tabular data analysis together with spatial operations  A `GeoDataFrame` (or *Feature Collection*) consists of:       **Geometries** or **features**: the spatial objects    **Attributes** or **properties**: columns with information about each spatial object       Geometries: Points, Linestrings and PolygonsSpatial **vector** data can consist of different types, and the 3 fundamental types are:* **Point** data: represents a single point in space.* **Line** data ("LineString"): represents a sequence of points that form a line.* **Polygon** data: represents a filled area.And each of them can also be combined in multi-part geometries (See https://shapely.readthedocs.io/en/stable/manual.htmlgeometric-objects for extensive overview). For the example we have seen up to now, the individual geometry objects are Polygons:<jupyter_code>print(countries.geometry[2])<jupyter_output><empty_output><jupyter_text>Let's import some other datasets with different types of geometry objects.A dateset about cities in the world (adapted from http://www.naturalearthdata.com/downloads/110m-cultural-vectors/110m-populated-places/, zip file is available in the `/data` directory), consisting of Point data:<jupyter_code>cities = geopandas.read_file("zip://./data/ne_110m_populated_places.zip")
print(cities.geometry[0])<jupyter_output><empty_output><jupyter_text>And a dataset of rivers in the world (from http://www.naturalearthdata.com/downloads/50m-physical-vectors/50m-rivers-lake-centerlines/, zip file is available in the `/data` directory) where each river is a (multi-)line:<jupyter_code>rivers = geopandas.read_file("zip://./data/ne_50m_rivers_lake_centerlines.zip")
print(rivers.geometry[0])<jupyter_output><empty_output><jupyter_text>The `shapely` libraryThe individual geometry objects are provided by the [`shapely`](https://shapely.readthedocs.io/en/stable/) library<jupyter_code>type(countries.geometry[0])<jupyter_output><empty_output><jupyter_text>To construct one ourselves:<jupyter_code>from shapely.geometry import Point, Polygon, LineString
p = Point(1, 1)
print(p)
polygon = Polygon([(1, 1), (2,2), (2, 1)])<jupyter_output><empty_output><jupyter_text>REMEMBER: Single geometries are represented by `shapely` objects:  If you access a single geometry of a GeoDataFrame, you get a shapely geometry object  Those objects have similar functionality as geopandas objects (GeoDataFrame/GeoSeries). For example:       `single_shapely_object.distance(other_point)` -> distance between two points    `geodataframe.distance(other_point)` ->  distance for each point in the geodataframe to the other point       Coordinate reference systemsA **coordinate reference system (CRS)** determines how the two-dimensional (planar) coordinates of the geometry objects should be related to actual places on the (non-planar) earth.For a nice in-depth explanation, see https://docs.qgis.org/2.8/en/docs/gentle_gis_introduction/coordinate_reference_systems.html A GeoDataFrame or GeoSeries has a `.crs` attribute which holds (optionally) a description of the coordinate reference system of the geometries:<jupyter_code>countries.crs<jupyter_output><empty_output><jupyter_text>For the `countries` dataframe, it indicates that it used the EPSG 4326 / WGS84 lon/lat reference system, which is one of the most used.  It uses coordinates as latitude and longitude in degrees, as can you be seen from the x/y labels on the plot:<jupyter_code>countries.plot()<jupyter_output><empty_output><jupyter_text>The `.crs` attribute is given as a dictionary. In this case, it only indicates the EPSG code, but it can also contain the full "proj4" string (in dictionary form). Under the hood, GeoPandas uses the `pyproj` / `proj4` libraries to deal with the re-projections.For more information, see also http://geopandas.readthedocs.io/en/latest/projections.html. ---There are sometimes good reasons you want to change the coordinate references system of your dataset, for example:- different sources with different crs -> need to convert to the same crs- distance-based operations -> if you a crs that has meter units (not degrees)- plotting in a certain crs (eg to preserve area)We can convert a GeoDataFrame to another reference system using the `to_crs` function. For example, let's convert the countries to the World Mercator projection (http://epsg.io/3395):<jupyter_code># remove Antartica, as the Mercator projection cannot deal with the poles
countries = countries[(countries['name'] != "Antarctica")]
countries_mercator = countries.to_crs(epsg=3395)  # or .to_crs({'init': 'epsg:3395'})
countries_mercator.plot()<jupyter_output><empty_output><jupyter_text>Note the different scale of x and y. ---**Exercise**: project the countries to [Web Mercator](http://epsg.io/3857), the CRS used by Google Maps, OpenStreetMap and most web providers. <!--countries.to_crs(epsg=3857)--> ---  Plotting our different layers together<jupyter_code>ax = countries.plot(edgecolor='k', facecolor='none', figsize=(15, 10))
rivers.plot(ax=ax)
cities.plot(ax=ax, color='red')
ax.set(xlim=(-20, 60), ylim=(-40, 40))<jupyter_output><empty_output><jupyter_text>See the [04-more-on-visualization.ipynb](04-more-on-visualization.ipynb) notebook for more details on visualizing geospatial datasets. ---**Exercise**: replicate the figure above by coloring the countries in black and cities in yellow <!--ax = countries.plot(edgecolor='w', facecolor='k', figsize=(15, 10))rivers.plot(ax=ax)cities.plot(ax=ax, color='yellow')ax.set(xlim=(-20, 60), ylim=(-40, 40))--> ---  A bit more on importing and creating GeoDataFrames  Note on `fiona`Under the hood, GeoPandas uses the [Fiona library](http://toblerity.org/fiona/) (pythonic interface to GDAL/OGR) to read and write data. GeoPandas provides a more user-friendly wrapper, which is sufficient for most use cases. But sometimes you want more control, and in that case, to read a file with fiona you can do the following:<jupyter_code>import fiona
from shapely.geometry import shape

with fiona.drivers():
    with fiona.open("data/ne_110m_admin_0_countries/ne_110m_admin_0_countries.shp") as collection:
        for feature in collection:
            # ... do something with geometry
            geom = shape(feature['geometry'])
            # ... do something with properties
            print(feature['properties']['name'])<jupyter_output><empty_output><jupyter_text>Constructing a GeoDataFrame manually<jupyter_code>geopandas.GeoDataFrame({
    'geometry': [Point(1, 1), Point(2, 2)],
    'attribute1': [1, 2],
    'attribute2': [0.1, 0.2]})<jupyter_output><empty_output><jupyter_text>Creating a GeoDataFrame from an existing dataframeFor example, if you have lat/lon coordinates in two columns:<jupyter_code>df = pd.DataFrame(
    {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],
     'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],
     'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],
     'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86]})
df['Coordinates']  = list(zip(df.Longitude, df.Latitude))
df['Coordinates'] = df['Coordinates'].apply(Point)
gdf = geopandas.GeoDataFrame(df, geometry='Coordinates')
gdf<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1063409376684031, 'fraction_numerical': 0.015088916831327466, 'mean_word_length': 5.748484848484848, 'pattern_counts': {'":': 0, '<': 80, '<?xml version=': 0, '>': 84, 'https://': 7, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '7032', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3515, 'n_tokens_neox': 3302, 'n_words': 1143, 'path': '01-introduction-geospatial-data.ipynb', 'repo_name': 'darribas/scipy2018-geospatial-data', 'size': '11134'}