The indices of a slice slice(start, stop[, step])
can be often represented by range(start, stop, step)
(or range(*slice(start, stop, step).indices(length))
when taking the underlying dimensions into account).
Let's say I have even two, multidimensional slices and the second slice could be used as a slice into the result of applying the first slice.
Example:
import numpy as np
data = np.random.rand(*(100, 100, 100))
a = data[::2, 7, :] # slice 1, a.shape = (50,100)
b = a[1, ::-1] # slice 2, b.shape = (100,)
I would like to find a general expression for calculating the single slice that does the same job. I know the dimensions of the underlying data structure.
c = data[2, 7, ::-1] # same as b
np.array_equal(b, c) # True
So, in getting from [::2, 7, :]
and [1, ::-1]
to [2, 7, ::-1]
in this example I would need a function like:
def concatenate_slices(shape, outer_slice, inner_slice):
...
return combined_slice
where outer_slice
and inner_slice
would both be a tuple of slices. In the example shape=(100, 100, 100)
and outer_slice=(slice(None, None, 2), 7, slice(None, None, None))
and inner_slice=(1, slice(None, None, -1))
.
I'm not sure how to do that efficiently.
My objects do something when __getitem__(slice)
is called (no intermediate views) and I want to do that only once but still have the possibility to have slices of slices.
As an extension (optional) I would like to know what happens if I have ellipses in the slices. How can I then make the combination?
No comments:
Post a Comment