You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决‘IndexError: index 774 is out of bounds for axis 0 with size 724’错误?

解决IndexError: index 774 is out of bounds for axis 0 with size 724错误

错误原因

  • 部分城市的坐标不在目标栅格c2019GDP_Clip.tif的覆盖范围内,导致temp_raster.index()返回的行索引超出了栅格实际行数(栅格仅724行,却返回了774行索引)。
  • 原代码每次循环重复打开栅格文件,效率极低。

解决方案与优化代码

核心改进点

  1. 栅格文件仅打开一次,避免重复IO操作
  2. 提前判断坐标是否在栅格范围内,过滤无效点
  3. 增加索引有效性校验,双重防止越界
  4. 处理缺失值,保证导出CSV的数据完整性

修改后的代码

import geopandas as gpd
import rasterio as rio

# 读取矢量数据
capital_cities = gpd.read_file(r'C:\Users\user\Desktop\SHP\Bangladesh_shapefile_Feature.shp')
capital_cities['Temp'] = 0

# 一次性打开栅格并读取数据
with rio.open(r'C:\Users\user\Desktop\Output raster\c2019GDP_Clip.tif') as temp_raster:
    temp_data = temp_raster.read(1)
    raster_bounds = temp_raster.bounds  # 获取栅格边界
    raster_rows, raster_cols = temp_data.shape  # 获取栅格行列数

    for idx, row in capital_cities.iterrows():
        city = row['DISTNAME']
        point = row['geometry']
        lon, lat = point.x, point.y

        # 判断点是否在栅格范围内
        if not (raster_bounds.left <= lon <= raster_bounds.right and raster_bounds.bottom <= lat <= raster_bounds.top):
            print(f"{city}: 坐标不在栅格覆盖范围内")
            capital_cities.at[idx, 'Temp'] = None
            continue

        # 获取栅格索引
        row_idx, col_idx = temp_raster.index(lon, lat)

        # 校验索引是否有效
        if 0 <= row_idx < raster_rows and 0 <= col_idx < raster_cols:
            temp_val = temp_data[row_idx, col_idx]
            print(f"{city}: {temp_val}")
            capital_cities.at[idx, 'Temp'] = temp_val
        else:
            print(f"{city}: 索引超出栅格范围")
            capital_cities.at[idx, 'Temp'] = None

# 导出为CSV文件
capital_cities.to_csv(r'C:\Users\user\Desktop\city_gdp_temp.csv', index=False)

额外说明

  • 导出的CSV会包含所有城市的数据,不在栅格范围内的城市Temp列会标记为None,方便后续处理。
  • 如果确认所有城市都应该在栅格范围内,需要检查矢量数据和栅格数据的坐标系是否一致(比如是否都是WGS84或UTM投影),坐标系不匹配也会导致坐标偏移,触发索引越界。

内容的提问来源于stack exchange,提问作者Syed Rafsan Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:20:53