David Pfau
David Pfau

Reputation: 813

Numpy array indexing with partial indices

I am trying to pull out a particular slice of a numpy array but don't know how to express it with a tuple of indices. Using a tuple of indices works if its length is the same as the number of dimensions:

ind = (1,2,3)

# these two values are the same
foo[1,2,3] 
foo[ind]

But if I want to get a slice along one dimension the same notation doesn't work:

ind = (2,3)

# these two values are not the same
foo[:,2,3]
foo[:,ind]

# and this isn't even proper syntax
foo[:,*ind]

So is there a way to use a named tuple of indices together with slices?

Upvotes: 3

Views: 2090

Answers (2)

BushMinusZero
BushMinusZero

Reputation: 1292

For accessing 2D arrays... I believe what you are suggesting should work. Be mindful that numpy arrays index starting from 0. So to pull the first and third column from the following matrix I use column indices 0 and 2.

import numpy as np
foo = np.array([[1,2,3],[4,5,6],[7,8,9]])

ind = (0,2)
foo[:,ind]

For accessing 3D arrays... 3D numpy arrays are accessed by 3 values x[i,j,k] where "i" represents the first matrix slice, or

[[ 0,  1,  2],
 [ 3,  4,  5],
 [ 6,  7,  8]]

from my example below. "j" represents the second matrix slice, or the rows of these matrices. And "k" represents their columns. i,j and k can be :, integer or tuple. So we can access particular slices by using two sets of named tuples as follows.

import numpy as np
foo2 = np.array([[[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8]],

              [[ 9, 10, 11],
               [12, 13, 14],
               [15, 16, 17]],

              [[18, 19, 20],
               [21, 22, 23],
               [24, 25, 26]]])

ind1 = (1,2)
ind2 = (0,1)

foo2[:,ind1,ind2]

Upvotes: 0

tobias_k
tobias_k

Reputation: 82929

Instead of using the : syntax you can explicitly create the slice object and add that to the tuple:

ind = (2, 3)
s = slice(None) # equivalent to ':'
foo[(s,) + ind] # add s to tuples

In contrast to using foo[:, ind], the result of this should be the same as foo[:,2,3].

Upvotes: 4

Related Questions