【问题标题】:Finding the slices from a list of coordinates in a numpy从 numpy 中的坐标列表中查找切片
【发布时间】:2021-11-15 02:58:02
【问题描述】:

我想从多维 numpy 中的坐标列表中检索切片列表。

我正在做的是以下(示例)。

首先,我声明我的基本数组:

base = np.zeros((8, 8, 4))

带有坐标列表:

coord = [slice(0, 1, None), slice(0, None, None)]

其次,我在numpy中创建了一个“掩码”:

base[coord] = -1

然后,我提取该区域的切片:

np.argwhere(base == -1)

我的问题是我不想修改 numpy 以提取坐标,当然副本不是可能的解决方案。获取切片的方法是什么或我应该做哪些修改?

【问题讨论】:

  • 为什么不使用pandasDataFrame,它将允许切片、过滤、切块等?

标签: python numpy


【解决方案1】:

您可以使用np.meshgrid 创建坐标数组,使用范围而不是切片:

import numpy as np

base = np.zeros((8, 8, 4))
coord = [range(0, 1), range(0, base.shape[1])]
coords_array = np.stack(np.meshgrid(*coord, indexing='ij'), -1).reshape(-1, len(coord))
print(coords_array)
# [[0 0]
#  [0 1]
#  [0 2]
#  [0 3]
#  [0 4]
#  [0 5]
#  [0 6]
#  [0 7]]

【讨论】:

    【解决方案2】:

    试试这个:

    import numpy as np
    base = np.zeros((8, 8, 4))
    coord = [slice(0, 1, None), slice(0, None, None)]
    all_coords = np.argwhere(base == base).reshape(*base.shape,base.ndim)  # (8,8,4,3)
    print(all_coords[coord].reshape(-1,base.ndim))
    

    输出:

    [[0 0 0]
     [0 0 1]
     [0 0 2]
     [0 0 3]
     [0 1 0]
     [0 1 1]
     [0 1 2]
     [0 1 3]
     [0 2 0]
     [0 2 1]
     [0 2 2]
     [0 2 3]
     [0 3 0]
     [0 3 1]
     [0 3 2]
     [0 3 3]
     [0 4 0]
     [0 4 1]
     [0 4 2]
     [0 4 3]
     [0 5 0]
     [0 5 1]
     [0 5 2]
     [0 5 3]
     [0 6 0]
     [0 6 1]
     [0 6 2]
     [0 6 3]
     [0 7 0]
     [0 7 1]
     [0 7 2]
     [0 7 3]]
    

    【讨论】:

      猜你喜欢
      • 2018-02-15
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 2012-09-07
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多