Introduction
One common task when working with geospatial data is extracting coordinates from point geometry columns in GeoPandas DataFrames. This can be useful for plotting points on a map or performing spatial analysis.
In this tutorial, we will explore different methods for extracting longitudes and latitudes from point geometry columns in GeoPandas DataFrames.
Creating a GeoPandas DataFrame
In this section, we will explore the steps involved in creating a basic GeoDataFrame using the provided 'data' dictionary. To begin, we can conveniently store our data into a pandas DataFrame:
import pandas as pddata = {'city_name':['Paris','London','Moscow', 'Istanbul'],'longitude':[2.3522,-0.1276,37.6173,28.9784],'latitude':[48.8566,51.5072,55.7558,41.0082]}df = pd.DataFrame(data)
and convert this pandas DataFrame into a GeoDataFrame:
import geopandasgdf = geopandas.GeoDataFrame(df,geometry=geopandas.points_from_xy(df.longitude, df.latitude),crs="EPSG:4326")
This will give us the following output:
city_name longitude latitude geometry0 Paris 2.3522 48.8566 POINT (2.35220 48.85660)1 London -0.1276 51.5072 POINT (-0.12760 51.50720)2 Moscow 37.6173 55.7558 POINT (37.61730 55.75580)3 Istanbul 28.9784 41.0082 POINT (28.97840 41.00820)
Extracting longitude and latitude values
To begin, we can examine the geometry type for each row using the following method:
gdf['geometry'].geom_type
Executing this will provide us with the resulting output:
0 Point1 Point2 Point3 Pointdtype: object
Extracting longitudes and latitudes using the .x and .y methods
To extract the longitudes from the geometry columns that contain only points, you can use the following code
gdf['geometry'].x0 2.35221 -0.12762 37.61733 28.9784dtype: float64
To extract the latitudes from the geometry columns that contain only points, you can use the following code:
gdf['geometry'].y0 48.85661 51.50722 55.75583 41.0082
If you want to create a new column in your DataFrame with longitude and latitude values, you can use the following code:
gdf['longitude_x'] = gdf['geometry'].xgdf['latitude_y'] = gdf['geometry'].y
Executing this will provide us with the resulting output:
city_name longitude latitude geometry longitude_x \0 Paris 2.3522 48.8566 POINT (2.35220 48.85660) 2.35221 London -0.1276 51.5072 POINT (-0.12760 51.50720) -0.12762 Moscow 37.6173 55.7558 POINT (37.61730 55.75580) 37.61733 Istanbul 28.9784 41.0082 POINT (28.97840 41.00820) 28.9784latitude_y0 48.85661 51.50722 55.75583 41.0082
References
| Links | Site |
|---|---|
| geopandas.GeoSeries.get_coordinates | geopandas.org |
| geometric_manipulations | geopandas.org |
