栅格采样后循环生成列表的格式调整技术求助
问题描述
我在指定目录下有多个栅格数据,需要利用包含兴趣点坐标的CSV文件(已读取为GeoDataFrame)提取band1的叶绿素浓度值。CSV内容如下:
point_id point_name latitude longitude geometry 0 1 'Forte dei Marmi' 10.2427 43.5703 POINT (10.24270 43.57030) 1 2 'La Spezia' 9.9030 44.0341 POINT (9.90300 44.03410) 2 3 'Orbetello' 11.2029 42.4488 POINT (11.20290 42.44880) 3 4 'Portoferraio' 10.3328 42.8080 POINT (10.33280 42.80800) 4 5 'Fregene' 12.1990 41.7080 POINT (12.19900 41.70800)
所有待采样的栅格存储在路径 raster_dir = 'C:/sentinel_3_processing/',最终目标是生成列数与栅格数量一致的DataFrame。目前采样功能正常,但输出格式不符合需求:
当前输出:
[[10.2427, 43.5703, 0.63], [10.2427, 43.5703, 0.94], ..., [12.199, 41.708, 1.62]]
期望输出:
[ [10.2427, 43.5703, 0.63, 0.94, ..., 3.07], ..., [12.199, 41.708, 0.96, ..., 1.62]] ]
原代码如下:
L = [] # final list that contains the other lists for p in csv_gdf['geometry']: # for all the point contained in the dataframe... for files in os.listdir(raster_dir): #...and for all the rasters in that folder... if files[-4:] == '.img': #...which extention is .img... r = rio.open(raster_dir + '\\' + files) # open the raster list_row = [] # read the raster band1 values at those coordinates... x = p.xy[0][0] y = p.xy[1][0] row, col = r.index(x, y) chl_value = r.read(1)[row, col] # append to list_row the coordinates ad then the raster value. list_row.append(p.xy[0][0]) list_row.append(p.xy[1][0]) list_row.append(round(float(chl_value), 2)) # then, append all the lists created in the loop to the final list L.append(list_row)
修改后的代码
import os import rasterio as rio L = [] # 预筛选所有.img格式的栅格文件,提升循环效率 raster_files = [f for f in os.listdir(raster_dir) if f.endswith('.img')] for p in csv_gdf['geometry']: # 为每个兴趣点初始化行列表,先加入坐标 list_row = [p.xy[0][0], p.xy[1][0]] x, y = p.xy[0][0], p.xy[1][0] # 遍历所有栅格,将当前点的采样值追加到行列表 for file in raster_files: with rio.open(os.path.join(raster_dir, file)) as r: row_idx, col_idx = r.index(x, y) chl_value = r.read(1)[row_idx, col_idx] list_row.append(round(float(chl_value), 2)) # 单个点的所有栅格采样完成后,再加入最终列表 L.append(list_row)
关键改动说明
- 调整循环逻辑:将行列表的初始化移到外层(兴趣点循环),先写入坐标,再在内层循环遍历所有栅格,把每个栅格的采样值依次追加到当前点的行列表中,最后将完整的行加入最终列表,实现每个点一行的格式。
- 预收集栅格文件:提前筛选出所有符合格式的栅格文件,避免每次循环都判断后缀,提升代码效率。
- 使用
with语句:自动管理栅格文件的打开与关闭,避免资源泄漏。 - 路径拼接优化:用
os.path.join替代字符串拼接,适配不同操作系统的路径格式,提升代码兼容性。
内容的提问来源于stack exchange,提问作者frog11235
相关产品推荐
相关产品推荐

