4

I want to slice a multidimensional ndarray but don't know which dimension I will slice on. Lets say we have a ndarray A with shape (6,7,8). Sometimes I need to slice on 1st dimension A[:,3,4], sometimes on third A[1,2,:].

Is there any symbol represent the ":"? I want to use it to generate an index array.

index=np.zeros(3)
index[0]=np.:
index[1]=3
index[2]=4
A[index]
Bo Shi
  • 41
  • 2
  • 1
    Yes, it is, but it works a little different: Use the builtin method `slice` to create 1D slices and index with a tuple of those slices. `slice(None,None)` represents the `:` – cel May 18 '15 at 10:15
  • 2
    This is exactly what you want http://stackoverflow.com/questions/24432209/python-index-an-array-using-the-colon-operator-in-an-arbitrary-dimension. – spacegoing May 18 '15 at 10:26

2 Answers2

5

The : slice can be explicitly created by calling slice(None) Here's 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]
cel
  • 30,017
  • 18
  • 97
  • 117
  • 1
    You don’t need to pass a slice object as second index item, you can just pass `1` again: `A[slice(None, None), 1]` (that’s the exact representation of what `A[:, 1]` means). – poke May 18 '15 at 10:30
  • 1
    @poke, yes good point. Also `slice(None)` seems sufficient. Seems like I tried to reinvent the wheel though - Chang Li linked a duplicate I think. – cel May 18 '15 at 10:32
1

You want index to be a tuple, with a mix of numbers, lists and slice objects. A number of the numpy functions that take an axis parameter construct such a tuple.

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

there are various ways constructing that 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 index can be list or tuple. It just can't be an array.

Starting with a list (or array) is handy in that you can modify values, but it is best to convert it to a tuple before use. I'd have to check the docs for the details, but there are circumstances where a list means something different from a tuple.

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

Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. Slice objects can be used in the construction in place of the [start:stop:step] notation. 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 constructing generic code that works on arrays of arbitrary dimension.

hpaulj
  • 221,503
  • 14
  • 230
  • 353