<jupyter_start><jupyter_text>Introduction to GeoPandasThis quick tutorial introduces the key concepts and basic features of GeoPandas to help you get started with your projects. ConceptsGeoPandas, as the name suggests, extends the popular data science library [pandas](https://pandas.pydata.org) by adding support for geospatial data. If you are not familiar with `pandas`, we recommend taking a quick look at its [Getting started documentation](https://pandas.pydata.org/docs/getting_started/index.htmlgetting-started) before proceeding.The core data structure in GeoPandas is the `geopandas.GeoDataFrame`, a subclass of `pandas.DataFrame`, that can store geometry columns and perform spatial operations. The `geopandas.GeoSeries`, a subclass of `pandas.Series`, handles the geometries. Therefore, your `GeoDataFrame` is a combination of `pandas.Series`, with traditional data (numerical, boolean, text etc.), and `geopandas.GeoSeries`, with geometries (points, polygons etc.). You can have as many columns with geometries as you wish; there's no limit typical for desktop GIS software.![geodataframe schema](../_static/dataframe.svg)Each `GeoSeries` can contain any geometry type (you can even mix them within a single array) and has a `GeoSeries.crs` attribute, which stores information about the projection (CRS stands for Coordinate Reference System). Therefore, each `GeoSeries` in a `GeoDataFrame` can be in a different projection, allowing you to have, for example, multiple versions (different projections) of the same geometry.Only one `GeoSeries` in a `GeoDataFrame` is considered the _active_ geometry, which means that all geometric operations applied to a `GeoDataFrame` operate on this _active_ column.User Guide    See more on [data structures in the User Guide](../docs/user_guide/data_structures.rst).Let's see how some of these concepts work in practice. Reading and writing filesFirst, we need to read some data. Reading filesAssuming you have a file containing both data and geometry (e.g. GeoPackage, GeoJSON, Shapefile), you can read it using `geopandas.read_file()`, which automatically detects the filetype and creates a `GeoDataFrame`. This tutorial uses the `"nybb"` dataset, a map of New York boroughs, which is part of the GeoPandas installation. Therefore, we use `geopandas.datasets.get_path()` to retrieve the path to the dataset.<jupyter_code>import geopandas

path_to_data = geopandas.datasets.get_path("nybb")
gdf = geopandas.read_file(path_to_data)

gdf<jupyter_output><empty_output><jupyter_text>Writing filesTo write a `GeoDataFrame` back to file use `GeoDataFrame.to_file()`. The default file format is Shapefile, but you can specify your own with the `driver` keyword.<jupyter_code>gdf.to_file("my_file.geojson", driver="GeoJSON")<jupyter_output><empty_output><jupyter_text>User Guide    See more on [reading and writing data in the User Guide](../docs/user_guide/io.rst). Simple accessors and methodsNow we have our `GeoDataFrame` and can start working with its geometry. Since there was only one geometry column in the New York Boroughs dataset, this column automatically becomes the _active_ geometry and spatial methods used on the `GeoDataFrame` will be applied to the `"geometry"` column. Measuring areaTo measure the area of each polygon (or MultiPolygon in this specific case), access the `GeoDataFrame.area` attribute, which returns a `pandas.Series`. Note that `GeoDataFrame.area` is just `GeoSeries.area` applied to the _active_ geometry column.But first, to make the results easier to read, set the names of the boroughs as the index:<jupyter_code>gdf = gdf.set_index("BoroName")
gdf["area"] = gdf.area
gdf["area"]<jupyter_output><empty_output><jupyter_text>Getting polygon boundary and centroidTo get the boundary of each polygon (LineString), access the `GeoDataFrame.boundary`:<jupyter_code>gdf['boundary'] = gdf.boundary
gdf['boundary']<jupyter_output><empty_output><jupyter_text>Since we have saved boundary as a new column, we now have two geometry columns in the same `GeoDataFrame`.We can also create new geometries, which could be, for example, a buffered version of the original one (i.e., `GeoDataFrame.buffer(10)`) or its centroid:<jupyter_code>gdf['centroid'] = gdf.centroid
gdf['centroid']<jupyter_output><empty_output><jupyter_text>Measuring distanceWe can also measure how far each centroid is from the first centroid location.<jupyter_code>first_point = gdf['centroid'].iloc[0]
gdf['distance'] = gdf['centroid'].distance(first_point)
gdf['distance']<jupyter_output><empty_output><jupyter_text>Note that `geopandas.GeoDataFrame` is a subclass of `pandas.DataFrame`, so we have all the pandas functionality available to use on the geospatial dataset — we can even perform data manipulations with the attributes and geometry information together.For example, to calculate the average of the distances measured above, access the 'distance' column and call the mean() method on it:<jupyter_code>gdf['distance'].mean()<jupyter_output><empty_output><jupyter_text>Making mapsGeoPandas can also plot maps, so we can check how the geometries appear in space. To plot the active geometry, call `GeoDataFrame.plot()`. To color code by another column, pass in that column as the first argument. In the example below, we plot the active geometry column and color code by the `"area"` column. We also want to show a legend (`legend=True`).<jupyter_code>gdf.plot("area", legend=True)<jupyter_output><empty_output><jupyter_text>Switching the active geometry (`GeoDataFrame.set_geometry`) to centroids, we can plot the same data using point geometry.<jupyter_code>gdf = gdf.set_geometry("centroid")
gdf.plot("area", legend=True)<jupyter_output><empty_output><jupyter_text>And we can also layer both `GeoSeries` on top of each other. We just need to use one plot as an axis for the other.<jupyter_code>ax = gdf["geometry"].plot()
gdf["centroid"].plot(ax=ax, color="black")<jupyter_output><empty_output><jupyter_text>Now we set the active geometry back to the original `GeoSeries`.<jupyter_code>gdf = gdf.set_geometry("geometry")<jupyter_output><empty_output><jupyter_text>User Guide    See more on [mapping in the User Guide](../docs/user_guide/mapping.rst). Geometry creationWe can further work with the geometry and create new shapes based on those we already have.  Convex hullIf we are interested in the convex hull of our polygons, we can access `GeoDataFrame.convex_hull`.<jupyter_code>gdf["convex_hull"] = gdf.convex_hull
ax = gdf["convex_hull"].plot(alpha=.5)  # saving the first plot as an axis and setting alpha (transparency) to 0.5
gdf["boundary"].plot(ax=ax, color="white", linewidth=.5)  # passing the first plot and setting linewitdth to 0.5<jupyter_output><empty_output><jupyter_text>BufferIn other cases, we may need to buffer the geometry using `GeoDataFrame.buffer()`. Geometry methods are automatically applied to the active geometry, but we can apply them directly to any `GeoSeries` as well. Let's buffer the boroughs and their centroids and plot both on top of each other.<jupyter_code># buffering the active geometry by 10 000 feet (geometry is already in feet)
gdf["buffered"] = gdf.buffer(10000)

# buffering the centroid geometry by 10 000 feet (geometry is already in feet)
gdf["buffered_centroid"] = gdf["centroid"].buffer(10000)
ax = gdf["buffered"].plot(alpha=.5)  # saving the first plot as an axis and setting alpha (transparency) to 0.5
gdf["buffered_centroid"].plot(ax=ax, color="red", alpha=.5)  # passing the first plot as an axis to the second
gdf["boundary"].plot(ax=ax, color="white", linewidth=.5)  # passing the first plot and setting linewitdth to 0.5<jupyter_output><empty_output><jupyter_text>User Guide    See more on [geometry creation and manipulation in the User Guide](../docs/user_guide/geometric_manipulations.rst). Geometry relationsWe can also ask about the spatial relations of different geometries. Using the geometries above, we can check which of the buffered boroughs intersect the original geometry of Brooklyn, i.e., is within 10 000 feet from Brooklyn.First, we get a polygon of Brooklyn.<jupyter_code>brooklyn = gdf.loc["Brooklyn", "geometry"]
brooklyn<jupyter_output><empty_output><jupyter_text>The polygon is a [shapely geometry object](https://shapely.readthedocs.io/en/stable/manual.htmlgeometric-objects), as any other geometry used in GeoPandas.<jupyter_code>type(brooklyn)<jupyter_output><empty_output><jupyter_text>Then we can check which of the geometries in `gdf["buffered"]` intersects it.<jupyter_code>gdf["buffered"].intersects(brooklyn)<jupyter_output><empty_output><jupyter_text>Only Bronx (on the north) is more than 10 000 feet away from Brooklyn. All the others are closer and intersect our polygon.Alternatively, we can check which buffered centroids are entirely within the original boroughs polygons. In this case, both `GeoSeries` are aligned, and the check is performed for each row.<jupyter_code>gdf["within"] = gdf["buffered_centroid"].within(gdf)
gdf["within"]<jupyter_output><empty_output><jupyter_text>We can plot the results on the map to confirm the finding.<jupyter_code>gdf = gdf.set_geometry("buffered_centroid")
ax = gdf.plot("within", legend=True, categorical=True, legend_kwds={'loc': "upper left"})  # using categorical plot and setting the position of the legend
gdf["boundary"].plot(ax=ax, color="black", linewidth=.5)  # passing the first plot and setting linewitdth to 0.5<jupyter_output><empty_output><jupyter_text>ProjectionsEach `GeoSeries` has its Coordinate Reference System (CRS) accessible at `GeoSeries.crs`. The CRS tells GeoPandas where the coordinates of the geometries are located on the earth's surface. In some cases, the CRS is geographic, which means that the coordinates are in latitude and longitude. In those cases, its CRS is WGS84, with the authority code `EPSG:4326`. Let's see the projection of our NY boroughs `GeoDataFrame`.<jupyter_code>gdf.crs<jupyter_output><empty_output><jupyter_text>Geometries are in `EPSG:2263` with coordinates in feet. We can easily re-project a `GeoSeries` to another CRS, like `EPSG:4326` using `GeoSeries.to_crs()`.<jupyter_code>gdf = gdf.set_geometry("geometry")
boroughs_4326 = gdf.to_crs("EPSG:4326")
boroughs_4326.plot()
boroughs_4326.crs<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08949416342412451, 'fraction_numerical': 0.007684824902723735, 'mean_word_length': 6.348820586132952, 'pattern_counts': {'":': 0, '<': 81, '<?xml version=': 0, '>': 81, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '27202', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3207, 'n_tokens_neox': 3005, 'n_words': 1154, 'path': 'doc/source/getting_started/introduction.ipynb', 'repo_name': 'dpa9694/geopandas', 'size': '10280'}