【问题标题】:Slicing numpy array with arrays of indices, some of which are out of bounds用索引数组切片numpy数组,其中一些超出范围
【发布时间】:2021-06-14 23:04:40
【问题描述】:

我正在使用形状为 (1, 1, ny, nx) 的 numpy 数组形式的图像数据,其中 nx 和 ny 通常约为 20000。目前,我通过以下方式提取 numpy 数组中任意位置的值:

image = np.array([[[[0.1, 0.2, 0.3],
                    [0.4, 0.5, 0.6],
                    [0.7, 0.8, 0.9]]]])
idx_y, idx_x = np.array([1, 2]), np.array([1, 0])
value_at_idx = image[0, 0, idx_y, idx_x]  ## == np.array([0.5, 0.7])

当我传入切片的索引数组包含超出图像数组范围的索引时,就会出现我的问题,即:

idx_y, idx_x = np.array([1, 2]), np.array([1, 10])
value_at_idx = image[0, 0, idx_y, idx_x]
Traceback (most recent call last):
  File "<input>", line 2, in <module>
IndexError: index 10 is out of bounds for axis 3 with size 3

我的目标是为超出范围的请求索引返回所有图像值(作为一维列表/数组)和 NaN,例如对于上面的示例,我将返回 np.array([0.5, nan])。当然,目前我有以下非numpy/低效的代码:

mask = ((idx_ra > 0) & (idx_ra < nx)) &\
       ((idx_dec > 0) & (idx_dec < ny))

value_at_idx = []
for idx, i_ra in enumerate(idx_ra):
    if mask[idx]:
        value_at_idx.append(imdata[0, 0, idx_dec[idx], i_ra])
    else:
        value_at_idx.append(float('NaN'))

但是,理想情况下,为了提高效率,我想要一个 numpy 实现。我只发现了类似于this issue 的帖子,其中超出范围的值被简单地忽略了。有什么帮助吗?谢谢!

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    试试这个实现,我不知道这有多有效,但试一试。 第一步是用np.nan填充数组

    def nan_padding(image):
        image_y = image.shape[2]
        image_x = image.shape[3]
    
        h_nan = np.full(shape=(image_y,1) ,fill_value=np.nan)
        new_image1 = np.hstack((h_nan, image.reshape((image_y, image_x)), h_nan))
    
        v_nan = np.full(shape=(1,image_x+2) ,fill_value=np.nan)
        return np.vstack((v_nan, new_image1, v_nan)).reshape((1,1,image_y+2, image_x+2))
    

    第二步是使用np.take进行索引:

    def nan_indexing(image, idx_y, idx_x):
        new_indices = (idx_y + 1) * image.shape[2] + idx_x + 1
        return np.take(image, new_indices, mode='clip')
    

    现在:

    padded_image = nan_padding(image)
    value_at_idx = nan_indexing(padded_image, idx_y, idx_x)
    print(value_at_idx)
    

    输入:

    image = np.array([[[[0.1, 0.2, 0.3],
                        [0.4, 0.5, 0.6],
                        [0.7, 0.8, 0.9]]]])
    idx_y, idx_x = np.array([1, 2]), np.array([1, 0])
    idx_y, idx_x = np.array([1, 2]), np.array([1, 10])
    

    输出:

    [0.5 0.7]
    [0.5 nan]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多