Python – A multidimensional array slice in an object

A multidimensional array slice in an object… here is a solution to the problem.

A multidimensional array slice in an object

I have a numpy array:

arr = numpy.arange(25 * 10 * 20)
arr.resize((25, 10, 20))

I would like to get a slice like this:

arr[3:6, 2:8, 7:9]

This one works:

index = [slice(3, 6), slice(2, 8), slice(7, 9)]
arr[index]

But this is not:

>>> index = slice([3, 2, 7], [6, 8, 9])
>>> arr[index]
TypeError: slice indices must be integers or None or have an __index__ method

Can it be done with a slice object? Or only 3 slice lists work?

Solution

>>> help(slice)
class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])

So we use slice(start, stop, step).

>>> import numpy as np
>>> x = np.arange(10)

## ERROR

>>> i=slice([1,3])
>>> x[i]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method

## OK

>>> i = slice(3,7,2)
>>> print(x)
[0 1 2 3 4 5 6 7 8 9]
>>> print(i)
slice(3, 7, 2)
>>> print(x[i])
[3 5]

For multidimensional:

>>> x = np.arange(12).reshape(3,4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> i = slice(0,3,1)
>>> i
slice(0, 2, 1)
>>> x[i,i]
array([[0, 1],
       [4, 5]])

Related Problems and Solutions