Skip to content

Instantly share code, notes, and snippets.

@lx-88
Created August 7, 2015 21:49
Show Gist options
  • Save lx-88/84dc09d0b9fc3c3be4b6 to your computer and use it in GitHub Desktop.
Save lx-88/84dc09d0b9fc3c3be4b6 to your computer and use it in GitHub Desktop.
Merge files within a directory when the ending of the filename matches a given string. Uses geopandas.
def concat_spatial_df(folder_to_search, ends_with=".shp"):
"""
Merge spatial data layers that meet the ending provided by ends_with and within
folder folder_to_search and it's children
import os
import pandas as pd
import geopandas
"""
# Find files to merge
shps_to_join = list()
for root, dirs, files in os.walk(folder_to_search, topdown=False):
for fn in files:
if fn.endswith(ends_with):
shps_to_join.append(os.path.abspath(os.path.join(folder_to_search, fn)))
# Merge all xsection shapefiles into one.
crs = None
dfs_to_join = list()
for fn in shps_to_join:
df = geopandas.GeoDataFrame.from_file(fn)
crs = df.crs
dfs_to_join.append(df)
merged_df = geopandas.GeoDataFrame(pd.concat(dfs_to_join), crs=crs)
return merged_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment