通过 geopandas 连接多个 shapefile

Concat multiple shapefiles via geopandas

我正在尝试通过执行以下操作来合并多个 shapefile:

import geopandas as gpd
import pandas as pd

for i in range(10,56):
    interesting_files = "/Users/m3105/Downloads/area/tl_2015_{}_arealm.shp".format(i)
    gdf_list = []
    for filename in sorted(interesting_files):
        gdf_list.append(gpd.read_file((filename)))
        full_gdf = pd.concat(gdf_list)

其中目录 /Users/m3105/Downloads/area 有几个形状文件,例如 tl_2015_01_arealm.shptl_2015_02_arealm.shp 一直到 tl_2015_56_arealm.shp。我想合并所有这些 shapefile 并避免重复它们的 headers。但是,每当我尝试使用上面的代码连接文件时,我都会收到以下错误:

ValueError: Null layer: u''

通常情况下,我知道如何将 csv 文件连接在一起,但我不知道如何连接 shapefile。我将不胜感激任何帮助

我无法测试这个,因为我没有你的数据,但你想要这样的东西(假设 python 3):

from pathlib import Path
import pandas
import geopandas

folder = Path("/Users/m3105/Downloads/area")
shapefiles = folder.glob("tl_2015_*_arealm.shp")
gdf = pandas.concat([
    geopandas.read_file(shp)
    for shp in shapefiles
]).pipe(geopandas.GeoDataFrame)
gdf.to_file(folder / 'compiled.shp')

如果像@Paul H 的回答那样使用pandas.concat,默认情况下不会保留某些地理信息,例如坐标参考系统(crs)。但它在使用如下方式时有效:

import os
import geopandas as gpd
import pandas as pd

file = os.listdir("Your folder")
path = [os.path.join("Your folder", i) for i in file if ".shp" in i]

gdf = gpd.GeoDataFrame(pd.concat([gpd.read_file(i) for i in path], 
                        ignore_index=True), crs=gpd.read_file(path[0]).crs)

这样,geodataframe 就会有你需要的 CRS

我没有足够的代表对上次提交发表评论,但在使用不同的 CRS 测试输入文件后,

gdf = gpd.GeoDataFrame(pd.concat([gpd.read_file(i) for i in path], 
                        ignore_index=True), crs=gpd.read_file(path[0]).crs)

应该是

gdf = gpd.GeoDataFrame(pd.concat([gpd.read_file(i).to_crs(gpd.read_file(path[0]).crs) for i in path], 
                        ignore_index=True), crs=gpd.read_file(path[0]).crs)