Python 是否用每个文件的唯一目录的一部分填充列?
我想添加一列,并用目录中每个文件的唯一地址填充该列: 例如: 假设每个子文件夹中有两个名为:Python 是否用每个文件的唯一目录的一部分填充列?,python,pandas,geopandas,Python,Pandas,Geopandas,我想添加一列,并用目录中每个文件的唯一地址填充该列: 例如: 假设每个子文件夹中有两个名为: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.
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
位置并填充新列
比如:
守则:
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
TypeError:'str'对象不支持项分配
TypeError回溯(最近一次调用上次)
在()
5#shpfile['col']=shpfile.split(“\\”)[-3]
6 shapefiles.append(geopandas.read_文件(shpfile))
---->7 shpfile['col']=shpfile.split(“\\”)[-3]
8除FionaValueError外,其他为ex:
9如果不是os.listdir(SHP文件):
TypeError:“str”对象不支持项分配
最后,连接的文件的列还将包含一个额外的列,该列将包含前面提到的来自其目录的编号。在拆分编号的父文件夹的路径之前,请尝试将
\\
替换为/
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')
shpfile
是文件路径的字符串表示形式。它不是数据帧。
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')