You need to enable JavaScript to run this app. 使用np.meshgrid与np.linspace构建高程图时触发“对象无法解析为整数”报错
优惠活动
大模型
产品
解决方案
定价
更多

使用np.meshgrid与np.linspace构建高程图时触发“对象无法解析为整数”报错

报错根源分析

触发object cannot be interpreted as an integer错误的核心原因,出在调用np.linspace时的参数类型不匹配:

  • np.linspace的第三个参数num(指定要生成的等间距样本点数量)必须为整数类型
  • 代码中传入的np.sqrt(pts)计算结果为浮点数(例如pts=1000000时得到的是1000.0而非整数1000),不符合参数要求,直接触发报错。

修复步骤

  1. 补全新手易遗漏的依赖导入:代码用到了numpy的所有数值函数,以及scipy.interpolate模块下的griddata插值方法,需要在代码最开头添加对应导入语句
  2. 对np.sqrt(pts)的计算结果做整数转换,符合np.linspace的参数要求即可。

修复后的完整可运行代码

# 补全依赖导入(新手容易漏写)
import numpy as np
from scipy.interpolate import griddata

data = np.loadtxt('Documents/location.txt') 
Long = data[:,0]
Lat = data[:,1]
Elev = data[:,2]

pts=1000000

# 把sqrt得到的浮点结果转为整数,符合linspace的参数要求
[x,y]=np.meshgrid(
    np.linspace(np.min(Long), np.max(Long), int(np.sqrt(pts))),
    np.linspace(np.min(Lat), np.max(Lat), int(np.sqrt(pts)))
)

z = griddata((Long, Lat), Elev, (x, y), method='linear')
x = np.matrix.flatten(x); #Gridded longitude
y = np.matrix.flatten(y); #Gridded latitude
z = np.matrix.flatten(z); #Gridded elevation

注意事项

  • 若你设置的pts不是完全平方数,int(np.sqrt(pts))会自动对结果取整,不影响网格生成逻辑,最终总网格点数会接近预期的pts值
  • 若后续运行出现name 'griddata' is not defined报错,就是未导入scipy.interpolate.griddata导致的,补全开头的导入语句即可解决。

内容的提问来源于stack exchange,提问作者Porsche Adams

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 13:06:07