python - 用每个文件的唯一目录的一部分填充一列?
问题描述
我想添加一列并用目录中每个文件的唯一地址部分填充它:
示例:假设我从每个名为的子文件夹中有两个文件: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
最后,连接的文件将具有它们的列以及一个额外的列,该列将包含其目录中的数字,如前所述。
解决方案
在拆分编号父文件夹的路径之前尝试替换\\
为。/
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')
推荐阅读
- git - 如何删除发布但不删除标签?
- python - 我怎样才能不从此代码中获取列表索引超出范围错误?
- exception - 通过代码在新的 JVM 上启动 JavaFX 应用程序
- android - 颤振:错误:找不到吸气剂:“暂停”。案例 AppLifecycleState.suspending
- android - Firebase Auth 无需登录即可注册
- paypal - PayPal Adaptive Payments 自动退还订单
- python - 将numpy的日期时间数组与时间戳进行比较
- javascript - 使用给定的 html 和 javascript(脚本标签)打开新窗口
- python - IndexError:维度超出范围(预计在 [-1, 0] 范围内,但得到 1)
- reactjs - React boostrap 表的响应不起作用