Python 用非缺失值迭代填充缺失值

Python Iteratively Fill Missing Values with Non-missing Values

提问人:Miss_Orchid 提问时间:9/18/2023 最后编辑:Miss_Orchid 更新时间:9/18/2023 访问量:45

问:

假设我有 10 个形状为 MxN 的数组。我想迭代遍历每个数组,并填充初始化数组中缺失值所在的值。

举个例子,让我们看一个 3x3 网格:

initial_array = np.full((3,3),-999)
array([[-999, -999, -999],
       [-999, -999, -999],
       [-999, -999, -999]])
final = np.full((3,3),-999)

然后我有几个数组:

b = array([[-999, -999,    1],
           [   1, -999, -999],
           [-999, -999, -999]])

c = array([[-999, -999,    2],
           [   2, -999, -999],
           [   2, -999, -999]])

d = array([[   3, -999, -999],
           [   3, -999, -999],
           [   3, -999,    3]])

我希望最终的数组是:

final = array([[   3, -999,    1],
               [   1, -999, -999],
               [   2, -999,    3]])

逻辑如下:

对于 final[0,0],在第三个数组 d 之前没有不丢失的值 (-999),因此最终值为 3。

对于 Final[1,0],第一个数组 b 中有一个 1 的实例,因此 [1,0] 的其余值对于其余数组来说并不重要。

由于 Final[:,1] 中没有值,因此这些值仍然缺失

目前,我知道如何做到这一点的最佳方法是遍历每个像素并运行“if-then”循环:

for i in range(0,initial_array.shape[0]):
  for j in range(0,initial_array.shape[1]):
    if initial_array[i,j] == -999:
        if next_array[i,j] > -999:
          final_array[i,j] = next_array[i,j]

但是,随着我们检查更多/更大的数组,这变得非常慢。有没有更好的方法?

Python 数组

评论

0赞 mozway 9/18/2023
请确保您的示例是否完整,并且未定义next_arrayfinal_array

答:

1赞 Aaron 9/18/2023 #1

您可以使用仅获取有效值的索引,然后使用指示以相反的顺序复制数据,以便一遍又一遍地具有优先级:np.wherebccd

import numpy as np
final = np.full((3,3),-999)

b = np.array([[-999, -999,    1],
              [   1, -999, -999],
              [-999, -999, -999]])

c = np.array([[-999, -999,    2],
              [   2, -999, -999],
              [   2, -999, -999]])

d = np.array([[   3, -999, -999],
              [   3, -999, -999],
              [   3, -999,    3]])

for arr in [d, c, b]:
    idx = np.where(arr != -999)
    final[idx]  = arr[idx]
print(final)
1赞 mozway 9/18/2023 #2

使用 3D 数组和 argmax 进行索引:

x = np.dstack([b, c, d])

idx, col = np.mgrid[:x.shape[0], :x.shape[1]]

final = x[idx, col, np.argmax(x != -999, axis=-1)]

艺术

x = np.dstack([b, c, d])

final = np.choose(np.argmax(x != -999, axis=-1), np.moveaxis(x, -1, 0))

输出:

array([[   3, -999,    1],
       [   1, -999, -999],
       [   2, -999,    3]])