【问题标题】:'numpy.float64' is not iterable for scipy function centre of mass'numpy.float64' 对于 scipy 函数质心不可迭代
【发布时间】:2019-12-21 14:19:15
【问题描述】:

我一直在尝试根据我的观测数据(.nc 格式)计算降水场的质心,但我不断收到错误消息:"TypeError: 'numpy.float64' object is not iterable"

我已设法将我的 netcdf 文件从 .nc 转换为 xarray 数据集,然后提取值以提供 (1, 90, 180) 数组,然后将其转换为 (90 , 180) 用于其他功能。然后我尝试计算阵列的质心,但它一直给我一条错误消息。

from scipy import ndimage

ncobsdata = Dataset('/home/data/20180380293.nc', mode = 'r')
obsdata = xr.open_dataset(xr.backends.NetCDF4DataStore(ncobsdata))
obs = obsdata.rain_total #shape = (1, 90, 180)

obsv = np.squeeze(obs) #I had to do this step to make it (90, 180)

CoM_obsv = ndimage.measurements.center_of_mass(obsv)

我希望得到质心结果,但我只是不断收到错误消息:

File "_____.py", line 10, in <module>
   CoM_obsv = ndimage.measurements.center_of_mass(obsv)
File "________/scipy/ndimage/measurements.py", line 1289, in center_of_mass
   return [tuple(v) for v in numpy.array(results).T]
TypeError: 'numpy.float64' object is not iterable

【问题讨论】:

  • 嗨,欢迎来到 SO!您的回溯中的哪一行给出了TypeError: 'numpy.float64' object is not iterable?这通常意味着您正在尝试遍历列表/可迭代对象,但您传入的对象似乎是单个 float64。
  • 感谢您的编辑。看起来您的 obsv 变量可能不是您期望的二维数组。你能做一个快速打印检查:print(obsv)print(obsv.shape) 看看它是什么?
  • @PeptideWitch print(obsv.shape) 给出结果(180, 270)。当我执行 print (obsv) 时,它会说:&lt;xarray.DataArray 'rain_total' (lat: 180, lon: 270)&gt;dtype=float32 我最初确实说 (90, 180) 但我认为这不会给我错误消息
  • 好的,看看 Xarray 文档,您可能需要访问 DataArray 对象的值。所以也许试试:CoM_obsv = ndimage.measurements.center_of_mass(obsv.values)

标签: python numpy scipy numpy-ndarray


【解决方案1】:

所以这里发生的是 obsobsv 变量都存储为 xarray.DataArrays - 这个类是常规 numpy 数组的包装器。要访问底层的 np.ndarray,您需要从对象中调用值:

CoM_obsv = ndimage.measurements.center_of_mass(obsv.values)

请注意,您不需要为 obsv = np.squeeze(obs) #I had to do this step to make it (90, 180) 执行此操作,因为 xarray.DataArrays 已有可用的挤压方法。

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2019-08-03
    • 2020-04-08
    • 2014-10-02
    • 1970-01-01
    相关资源
    最近更新 更多