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

Pysheds中`nodata`值无法匹配数组dtype的报错解决求助

解决Pysheds中nodata值无法匹配数组 dtype 的错误

问题场景

运行Pysheds处理DEM数据时,执行fdir = grid.flowdir(inflated_dem)语句触发如下错误:

代码示例

import numpy as np
from pysheds.grid import Grid

# 从栅格实例化网格
dem_file = 'CLSA_LiDAR.tif'
grid = Grid.from_raster(dem_file)
dem = grid.read_raster(dem_file)

# 处理平坦区域并计算流向
inflated_dem = grid.resolve_flats(dem)
fdir = grid.flowdir(inflated_dem)

# 计算汇水量
acc = grid.accumulation(fdir)

报错信息

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.11/dist-packages/pysheds/sview.py in __new__(cls, input_array, viewfinder, metadata)
     84         try:
---> 85             assert np.can_cast(viewfinder.nodata, obj.dtype, casting='safe')
     86         except:

TypeError: can_cast() does not support Python ints, floats, and complex because the result used to depend on the value.
This change was part of adopting NEP 50, we may explicitly allow them again in the future.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
4 frames
/usr/local/lib/python3.11/dist-packages/pysheds/sview.py in __new__(cls, input_array, viewfinder, metadata)
     85             assert np.can_cast(viewfinder.nodata, obj.dtype, casting='safe')
     86         except:
---> 87             raise TypeError('`nodata` value not representable in dtype of array.')
     88         # Don't allow original viewfinder and metadata to be modified
     89         viewfinder = viewfinder.copy()

TypeError: `nodata` value not representable in dtype of array.

错误原因

  1. Numpy版本兼容问题:Numpy 1.24+ 采纳了NEP 50规范,np.can_cast()不再支持直接检查Python标量(如int/float)与数组dtype的兼容性,而Pysheds的sview.py中仍使用该逻辑进行nodata值校验。
  2. 数据类型不匹配:原始DEM的nodata值类型与处理后inflated_dem的数组dtype不兼容,比如DEM为无符号整数类型,但nodata是负数或浮点数,导致无法安全转换。

解决方案

1. 统一nodata值与数组dtype

先检查当前数据的类型和nodata值,再转换为兼容的类型:

# 查看当前DEM的dtype和nodata值
print("DEM dtype:", dem.dtype)
print("Grid nodata:", grid.nodata)

# 将DEM转换为能容纳nodata值的类型(如float32或int32)
dem = dem.astype(np.float32)
# 同步更新grid的nodata值类型
grid.nodata = np.float32(grid.nodata)

# 重新处理平坦区域并计算流向
inflated_dem = grid.resolve_flats(dem)
fdir = grid.flowdir(inflated_dem)

2. 调用flowdir时显式指定nodata参数

直接传入与inflated_dem dtype匹配的nodata值,绕过自动校验逻辑:

inflated_dem = grid.resolve_flats(dem)
# 显式传入类型匹配的nodata值
fdir = grid.flowdir(inflated_dem, nodata=np.array(grid.nodata, dtype=inflated_dem.dtype))

3. 降级Numpy版本(临时方案)

如果不想修改代码,可以降级到Numpy 1.23.x版本,恢复旧的can_cast()逻辑:

pip install numpy==1.23.5

内容的提问来源于stack exchange,提问作者Kay Khaing Kyaw

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:20:03