How to represent ":" in numpy

I want to slice a multidimensional ndarray but don't know which dimension I am slicing. Let's say we have an ndarray A with shape (6,7,8). Sometimes I need to crop the 1st dimension A [:, 3,4], sometimes on the 3rd A [1,2 ,:].

Is there any symbol for ":"? I want to use it to create an array of indices.

index=np.zeros(3)
index[0]=np.:
index[1]=3
index[2]=4
A[index]

      

+3


source to share


2 answers


A slice :

can be explicitly created by calling slice(None)

Here is a short example:



import numpy as np
A = np.arange(9).reshape(3, -1)

# extract the 2nd column
A[:, 1]

# equivalently we can do
cslice = slice(None) # represents the colon
A[cslice, 1]

      

+4


source


You want it to index

be a tuple, with a combination of numbers, lists and slice

objects. A number of functions numpy

that take a parameter axis

create such a set.

A[(slice(None, None, None), 3, 4)]  # == A[:, 3, 4]

      

there are various ways to construct this tuple:

index = (slice(None),)+(3,4)

index = [slice(None)]*3; index[1] = 3; index[2] = 4

index = np.array([slice(None)]*3]; index[1:]=[3,4]; index=tuple(index)

      



In this case, it index

can be a list or a tuple. It just can't be an array.

Triggering with a list (or array) is convenient because you can change values, but it's better to use it before the tuple before using it. I will need to check the docs for details, but there are circumstances where a list means something other than a tuple.

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

Remember that slicing a tuple can always be constructed as obj and used in x [obj] notation. Slice objects can be used in construction instead of the [start: stop: step] designation. For example, x [1:10: 5, :: - 1] can also be implemented as obj = (slice (1,10,5), slice (None, None, -1)); x [obj]. This can be useful for generating generic code that works with arrays of arbitrary dimensions.

+1


source