【问题标题】:Filling a 2D array with simple values. Indexing goes wrong用简单值填充二维数组。索引出错
【发布时间】:2019-09-18 10:37:32
【问题描述】:

我正在为 QGIS 插件填充一个新的栅格层,其中包含值。要重新创建我使用 Numpy 数组的栅格。在一个循环中,我用新值填充单元格。对于此示例,我使用的是占位符值,但该部分工作正常。代码末尾的索引是我出现问题的地方。在这种情况下,只有最后一个单元格填充了我想要的值...

  for x1, y1 in np.ndenumerate(rast_int_newLU):
      for x2, y2 in np.ndenumerate(rast_int_oldLU):
          if x1 == x2:
             valueB = rast_int_oldLU[x1]
             valueA = rast_int_newLU[x2]

             dfkey = int(20)
             dt = np.float32

             a = np.ones(rast_int_oldLU.shape, dtype=dt)
             np.around(a, 4)
             indexx = x1[0]
             indexy = x1[1]
             a[indexx][indexy] = dfkey
      print("Output:")
      print(a)

有人知道哪里出错了吗?

【问题讨论】:

  • “索引出错”是什么意思?如果有错误信息,请将其包含在问题中。
  • 为什么a会在循环深处创建?
  • 该死,这是一个典型的错误。当数组在循环外创建时,一切都按预期工作!谢谢询问@hpaulj

标签: numpy indexing raster


【解决方案1】:

在@hpaulj 的帮助下,我想通了!这是一个经典的初学者错误。该数组是在循环内创建的,因此将其默认值重置回 1。只有最后一次迭代不会发生这种情况,因此单元格没有转换回 1。正确的代码是:

dt = np.float32
a = np.ones(rast_int_oldLU.shape, dtype=dt)

for x1, y1 in np.ndenumerate(rast_int_newLU):
      for x2, y2 in np.ndenumerate(rast_int_oldLU):
          if x1 == x2:
             valueB = rast_int_oldLU[x1]
             valueA = rast_int_newLU[x2]

             dfkey = int(20)

             np.around(a, 4)
             indexx = x1[0]
             indexy = x1[1]
             a[indexx][indexy] = dfkey
      print("Output:")
      print(a)

现在所有值都是 20。从逻辑上讲,这个值可以轻松更改 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多