Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
David Pfau Avatar asked Nov 27 '25 07:11

David Pfau


1 Answers

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].

like image 119
tobias_k Avatar answered Nov 28 '25 22:11

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!