[英]Finding the slices from a list of coordinates in a numpy
I want to retrieve a list of slices from a list of coordinates in a multidimensional numpy.我想从多维 numpy 中的坐标列表中检索切片列表。
What I am doing is the following (example).我正在做的是以下(示例)。
First, I declare my base array:首先,我声明我的基本数组:
base = np.zeros((8, 8, 4))
with a list of coordinates:带有坐标列表:
coord = [slice(0, 1, None), slice(0, None, None)]
Second, I create a "mask" in the numpy:其次,我在 numpy 中创建了一个“掩码”:
base[coord] = -1
Then, I extract the slices of that area:然后,我提取该区域的切片:
np.argwhere(base == -1)
The problem I have is that I don't want to modificate the numpy in order to extract the coordinates, and of course a copy is not a possible solution.我遇到的问题是我不想修改 numpy 以提取坐标,当然副本不是可能的解决方案。 What's the way to do it or what modification I should do for obtaining the slices?这样做的方法是什么,或者我应该为获得切片做哪些修改?
You can create the array of coordinates with np.meshgrid
, using ranges instead of slices:您可以使用范围而不是切片创建坐标数组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(coords))
print(coords_array)
# [[0 0]
# [0 1]
# [0 2]
# [0 3]
# [0 4]
# [0 5]
# [0 6]
# [0 7]]
Try this:尝试这个:
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))
Output: Output:
[[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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.