Reputation: 89
I want to retrieve a list of slices from a list of coordinates in a multidimensional 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:
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. What's the way to do it or what modification I should do for obtaining the slices?
Upvotes: 0
Views: 374
Reputation: 59731
You can create the array of coordinates with np.meshgrid
, using ranges instead of slices:
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]]
Upvotes: 2
Reputation: 15872
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:
[[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]]
Upvotes: 1