【问题标题】:Concat multiple shapefiles via geopandas通过 geopandas 连接多个 shapefile
【发布时间】:2022-05-17 07:10:36
【问题描述】:

我正在尝试通过实现以下方式来组合多个 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 有几个shapefile,例如tl_2015_01_arealm.shptl_2015_02_arealm.shp 一直到tl_2015_56_arealm.shp。我想结合所有这些 shapefile 并避免重复它们的标题。但是,每当我尝试使用上面的代码连接文件时,都会收到以下错误:

ValueError: Null layer: u''

通常,我知道如何将 csv 文件连接在一起,但我注意到如何连接 shapefile。非常感谢任何帮助

【问题讨论】:

  • 您的代码中似乎有几个错误能够运行:interesting_files 是单个字符串,因此使用 for filename in sorted(interesting_files): 循环遍历它将遍历该文件名的单个字符。此外,pd.concat(gdf_list) 应该在 for 循环之外。

标签: python geopandas


【解决方案1】:

我无法测试这个,因为我没有你的数据,但你想要这样的东西(假设 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')

【讨论】:

    【解决方案2】:

    如果像@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

    【讨论】:

    • 我有大型数据集,这工作得非常快!
    • 这么高效!
    【解决方案3】:

    我没有足够的代表来评论上次提交的内容,但是在使用不同的 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2021-06-22
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多