Skip to main content
56 votes

Converting Pandas DataFrame to GeoDataFrame

Update 201912: The official documentation at https://geopandas.readthedocs.io/en/latest/gallery/create_geopandas_from_pandas.html does it succinctly using geopandas.points_from_xy like so: gdf = ...
weiji14's user avatar
  • 1,751
55 votes

Finding nearest point in other GeoDataFrame using GeoPandas

If you have large dataframes, I've found that scipy's cKDTree spatial index .query method returns very fast results for nearest neighbor searches. As it uses a spatial index it's orders of magnitude ...
JHuw's user avatar
  • 659
31 votes
Accepted

Finding nearest point in other GeoDataFrame using GeoPandas

You can directly use the Shapely function Nearest points (the geometries of the GeoSeries are Shapely geometries): from shapely.ops import nearest_points # unary union of the gpd2 geomtries pts3 = ...
gene's user avatar
  • 55.2k
24 votes
Accepted

Shapely coordinate sequence to GeoDataFrame

Make a shapely polygon geometry from coordinate pairs. Pass the polygon to GeoDataFrame constructor as a list. import geopandas as gpd from shapely.geometry import Polygon coords = [(151....
Kadir Şahbaz's user avatar
22 votes
Accepted

Reading raw data into geopandas

You can pass the json directly to the GeoDataFrame constructor: import geopandas as gpd import requests data = requests.get("https://data.cityofnewyork.us/api/geospatial/arq3-7z49?method=export&...
user2856's user avatar
  • 67.7k
20 votes

Finding nearest point in other GeoDataFrame using GeoPandas

As of v0.10.0 geopandas supports sjoin_nearest natively - see here. Example: Get the nearest distances between points of two different GeoDataFrames or within one GeoDataFrame. Note that you should ...
rdmolony's user avatar
  • 323
19 votes

Change marker size in plot with GeoPandas

In geopandas >= 0.3 (released September 2017), the plotting of points is based on the scatter plot method of matplotlib under the hood, and this accepts a variable markersize. So now you can actually ...
joris's user avatar
  • 3,933
17 votes
Accepted

TypeError: Input geometry column must contain valid geometry objects

I tested the following and works fine: from shapely import wkt import pandas as pd df = pd.DataFrame( {'name': ['testname', 'testname'], 'geom': ['MULTIPOLYGON (((21.78 40.36, ... 21.77 40....
pan's user avatar
  • 567
16 votes
Accepted

Quick way to get WKT from a GeoDataFrame's geometries in GeoPandas?

UPDATE: As of GeoPandas 0.9, there is a to_wkt method. mydf['wkt'] = mydf.geometry.to_wkt() Yes, there is to_wkt method in semi-private array module. I think it should be public in future, will have ...
martinfleis's user avatar
  • 2,447
14 votes
Accepted

GeoPandas to_file() saves GeoDataFrame without coordinate system

I have come across this behavior before. You need to explicitly pass the well known text (crs_wkt) string to the to_file() method. The string will then get passed to fiona.open(), which writes out ...
Nxaunxau's user avatar
  • 3,933
12 votes
Accepted

Merging a geodataframe and pandas dataframe based on a column

You should specify a common key using on parameter. I removed merged_ prefix for legibility. df = spatial_df.merge(tab_df, on='mukey', how='left') # df = tab_df.merge(spatial_df, on='mukey', how='...
Kadir Şahbaz's user avatar
11 votes
Accepted

Adding elevation, name and description in GeoJSON when converting DataFrame with Python

Using what i learned from the answer of @gene this solution avoids the use of iterrows because iterrows have performance issues. Valid for Python 3.X import pandas as pd import geojson def ...
jrovegno's user avatar
  • 293
11 votes

Finding distance of consecutive points in a GeoPandas data frame

This is how I would do it import pandas as pd import geopandas as gpd df = pd.DataFrame() df['lat'] = [42, 42.1, 43, 43.2, 43.9] df['lon'] = [-120, -119, -118.2, -118, -117.2] gdf = gpd.GeoDataFrame(...
guibar's user avatar
  • 211
11 votes
Accepted

"Copy" Image coordinates to another image that is nd.array

Save result array (rf_array) as in the following lines: rf_array = df_join['Prediction'].values # returns numpy.ndarray rf_array = rf_array.reshape(img.shape[0], img.shape[1]) # rf_array = rf_array....
Kadir Şahbaz's user avatar
11 votes
Accepted

Creating polyline from list of QgsPoints using PyQGIS

Solution using sample data to run in QGIS Python Editor: import pandas as pd # Creating sample data dato = pd.DataFrame(data = [[0, 0], [2, 4], [10, 10]]) # Rename column headers dato.columns = ['...
Noura's user avatar
  • 3,439
10 votes
Accepted

Plotting a CSV with coordinates one row at a time via GeoPandas

The following script saves an image for each earthquake point in a single plot. from shapely.geometry import Point from geopandas import GeoDataFrame import geopandas as gpd import pandas as pd ...
Kadir Şahbaz's user avatar
9 votes

Finding nearest point in other GeoDataFrame using GeoPandas

Figured it out: def min_dist(point, gpd2): gpd2['Dist'] = gpd2.apply(lambda row: point.distance(row.geometry),axis=1) geoseries = gpd2.iloc[gpd2['Dist'].argmin()] return geoseries Of ...
RedM's user avatar
  • 1,623
9 votes
Accepted

Getting elevation for multiple lat long coordinates in Python

Don't know if this is the simplest way, but it saves gathering elevation data. The USGS-National Map has a REST service that you can use to query elevation for lat/lon coords. Service url: https://...
bebego's user avatar
  • 1,173
9 votes
Accepted

Creating QgsVectorLayer from Pandas dataframe

Your method is the simplest. However, there is an alternative by creating a new layer in QGIS and completing it by browsing your dataframe pandas. import pandas as pd # Declaration of my pandas ...
Vincent Bré's user avatar
  • 4,110
9 votes

Attribute Table into pandas DataFrame-PyQGIS

You can try: import pandas as pd lyr = QgsProject.instance().mapLayersByName('ok_ak_riks')[0] #List all columns you want to include in the dataframe. I include all with: cols = [f.name() for f in lyr....
Bera's user avatar
  • 76.2k
9 votes
Accepted

Joining two Pandas DataFrames based on lat, long as fields

Create Pandas DataFrame Create GeoPandas DataFrame using #1 Create Buffer for Points sjoin both GeoDataFrame df1 = pd.DataFrame({ 'name': ['post', 'sutter', 'oak'], 'Lat': [37.788151, ...
Aman Bagrecha's user avatar
8 votes
Accepted

Building GeoDataFrame row by row

I don't think that a row by row building would have better performance. I've tested. Result: import geopandas as gpd import pandas as pd from shapely.geometry import Point d = {'007': {'name': 'A', '...
Kadir Şahbaz's user avatar
8 votes
Accepted

Read a GDB table into a pandas dataframe in ArcPy

You can use da.SearchCursor: import arcpy import pandas as pd table = r"C:\GIS\ArcMap_default_folder\Default.gdb\grids" columns = [f.name for f in arcpy.ListFields(table) if f.type!="...
Bera's user avatar
  • 76.2k
7 votes

Making shapefile from Pandas dataframe?

For ArcMap you need to define the Projection before exporting to Shapefile. import geopandas df = geopandas.GeoDataFrame(df, geometry='geometry') # proj WGS84 df.crs= "+proj=longlat +ellps=WGS84 +...
Ivan Moran's user avatar
7 votes

Geopandas: Write layer back into GeoDataBase

As with Fiona where you can specify the driver when you save a layer, you can do the same thing with GeoPandas (Writing Spatial Data) GeoDataFrames can be exported to many different standard ...
gene's user avatar
  • 55.2k
7 votes
Accepted

Groupby Ploting - give each plot title/name

If you want to represent the continents side by side, you have to create subplots on the same fig. To do so, you can iterate through your group of continents. Here is an example: import geopandas as ...
Delforge's user avatar
  • 332
7 votes

Error when converting a pandas DataFrame to a GeoDataFrame

Your lon, lat cols are object types. Cast them to floats: geometry = geopandas.points_from_xy(df.longitude.astype('float32'), df.latitude.astype('float32')) #OR geometry = geopandas.points_from_xy(df[...
user2856's user avatar
  • 67.7k
7 votes
Accepted

Mapping multiple polygons on Folium

If you use the data of Converting a column with coordinates in Pandas to GeoPandas, there is a problem with your location value or with your data The data in the GeoDataFrame x1,y1,x2,y2 = gdf['...
gene's user avatar
  • 55.2k
7 votes
Accepted

Pandas DataFrame to GeoDataFrame with Polygon geometry using groupby and lambda

Instead of using apply this can be done using the agg method with named aggregations. The only thing is that agg cannot yet operate on multiple columns, so the points must be condensed to a single ...
Shawn's user avatar
  • 1,867
7 votes
Accepted

Converting Pandas column with featurecollection to GeoJSON

You can use the following code. Just specify json_string_column and output file path. import json import pandas as pd import geopandas as gpd # df = YOUR DATAFRAME json_string_column = "...
Kadir Şahbaz's user avatar

Only top scored, non community-wiki answers of a minimum length are eligible