I am failing to understand how the function slice() relates to the usual Numpy indexing notation.
test = np.random.rand(4,4,4)
test[:,0:1,2]
>>> array([[0.73897606],
[0.68005618],
[0.32831257],
[0.36882484]])
but I cannot see what is about to go on now
test[slice(None),slice(0,1),slice(2,3)]
>>>> array([[[0.73897606]],
[[0.68005618]],
[[0.32831257]],
[[0.36882484]]])
Some experiments seem to confirm that slice(None)
is equivalent to :
, slice(0,1)
is equivalent to 0:1
, but slice(2,3)
is equivalent to 2
, as an index.
How to describe the [:,0:1,2]
slicing using the slice()
function?
Could somebody please give us a hint? I also do not get where the shape of the second output comes from, many thanks
EDIT - ADDITIONAL BACKGROUND
What I would like to be able to do is dynamically slice an array, given an input.
For example, given an array S
with shape (10,10,10,10), the user might select two variables to plot over, keeping the other two fixed at a selected location.
For example, (surface)plot the first and third, keeping the second and fourth at indeces say (2,3).
I can pass then the array S[:,2,:,3]
.
Following the answer in Dynamically slice an array, I though I would have something like
axis_to_plot_1 = 0
axis_to_plot_2 = 2
axis_to_slice_1 = 1
index_to_consider_1 = 2
axis_to_slice_2 = 3
index_to_consider_2 = 3
slc = [slice(None)] * len(S.shape)
slc[axis_to_slice_1] = slice(index_to_consider_1, index_to_consider_1 +1)
slc[axis_to_slice_2] = slice(index_to_consider_2, index_to_consider_2+1)
this would solve my issue, I could slice()
for both the :
(variable to consider when plotting) and "i" indexing cases (section on remaining dimensions).
How is the above dynamical slicing over two axes best implemented, any ideas please?