1

I have a numpy nd array with the following shape as an example:

import numpy as np

# Note this can be variable and have different dimensions each time
shape = [100, 100, 100, 5]
array = np.zeros(shape)

Now what I want to do is address the last dimension, so I need something like:

array[:, :, :, i] = something

But I cannot hard code it like this as the dimensions can change depending on the input. So is there a way to index the last dimension of an nd-array?

1 Answer 1

4

Yup:

array[..., i] = something

That's a literal ... there, not a placeholder for something else you're expected to write.

Sign up to request clarification or add additional context in comments.

2 Comments

did not know about this one, thanks. Also nice to know that array[...,i,:], and array[i,...] work as expected. If one had a large array (many dimensions), would there be a way to get at the nth index or nth to last index other than stacking :s at one end?
@Dan: The easiest way I know of would be to create a view of the array with the desired axis moved to the front using numpy.rollaxis, then index the new view. For example, to access index k in the nth axis, we'd use numpy.rollaxis(array, n)[k].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.