首页 > 解决方案 > 用每个文件的唯一目录的一部分填充一列?

问题描述

我想添加一列并用目录中每个文件的唯一地址部分填充它:

示例:假设我从每个名为的子文件夹中有两个文件:45554因此32456 它们的路径如下:

C:\Users\user\Desktop\SHAPE\45554\INS\INS.shp
C:\Users\user\Desktop\SHAPE\45554\INB\INB.shp
C:\Users\user\Desktop\SHAPE\32456\INS\INS.shp
C:\Users\user\Desktop\SHAPE\32456\INB\INB.shp

所以我需要提取每一行-3的位置并填充新列。

喜欢:

   new_col
     45554
     45554
     32456
     32456
     etc..

编码:

folder = path.Path(r"C:\Users\user\Desktop\SHAPE")
    shapefiles = []
        for shpfile in glob.iglob('**/Desktop/SHAPE/**/' ,recursive = True):
            try:
                shapefiles.append(geopandas.read_file(shpfile))
                shpfile['col'] = shpfile.split("\\")[-3]
            except FionaValueError as ex:
                if not os.listdir(shpfile):
                    #print(f'{shpfile} is empty')
        gdf = pd.concat(shapefiles, sort=True).pipe(geopandas.GeoDataFrame)
        gdf.to_file(folder / 'compiled.shp')

这给出了:

TypeError: 'str' object does not support item assignment
TypeError                                 Traceback (most recent call last)
<ipython-input-84-bc0ddf8da6d3> in <module>()
      5             #shpfile['col'] = shpfile.split("\\")[-3]
      6             shapefiles.append(geopandas.read_file(shpfile))
----> 7             shpfile['col'] = shpfile.split("\\")[-3]
      8         except FionaValueError as ex:
      9             if not os.listdir(shpfile):

TypeError: 'str' object does not support item assignment

最后,连接的文件将具有它们的列以及一个额外的列,该列将包含其目录中的数字,如前所述。

标签: pythonpandasgeopandas

解决方案


在拆分编号父文件夹的路径之前尝试替换\\为。/

folder = path.Path(r"C:\Users\user\Desktop\SHAPE")
shapefiles = []
    for shpfile in glob.iglob('**/Desktop/SHAPE/**/' ,recursive = True):
        try:
            shapefiles.append(geopandas.read_file(shpfile))
            shpfile['col'] = shpfile.replace('\\','/').split("/")[-3]
        except FionaValueError as ex:
            if not os.listdir(shpfile):
                #print(f'{shpfile} is empty')
    gdf = pd.concat(shapefiles, sort=True).pipe(geopandas.GeoDataFrame)
    gdf.to_file(folder / 'compiled.shp')

推荐阅读