2

Given a numpy array and a __getitem__-type index, is there an idiomatic way to get the corresponding slice of the array, that would always return an array and never a scalar?

Examples of valid indices include: an int, a slice, an ellipsis or a tuple of the above.

Say I have an array like this:

a = np.array([[1,2],[3,4]])

I am looking for an operation that would be equivalent to a[whatever] in all cases except when a[whatever] returns a scalar (for example, a[1,1]). In those cases I'd like this alternative operation to return a single-element array instead.

2
  • 3
    It might be worth clarifying that you want a 1D vector returned in place of a scalar, which I think is implied. (since a single-element array can have any number of dimensions). I have, in the past required that any slice of a 2D table always return a 2D table, in which case I used numpy.atleast_2d inside a table class that I wrote myself that mirrored many of array methods. It would probably break all kinds of stuff if you were able to get atleast_*D behavior out of a numpy array. Commented May 5, 2011 at 18:53
  • 2
    One possible use I can think of is when you always want the result to be a view, so that modifying it changes the original. If that is what is desired, atleast_Nd isn't good enough - probably need to convert the int indices to slices. Commented May 5, 2011 at 19:03

3 Answers 3

6

If you just want to return a single-element array in cases where a scalar would otherwise be returned, why not just use numpy.atleast_1d on the result of the slice?

E.g.:

import numpy as np
x = np.arange(100).reshape(10,10)
print x[0,0]
print np.atleast_1d(x[0,0])
print np.atleast_1d(x[:,:3])
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this. Is there a neat way to preserve the type of the array (I am using a subclass of ndarray and would like the result to be of the same type as x).
I should also note that I don't always know the type of x a priori.
@aix - Unfortunately, there's no np.asanyarray equivalent for np.atleast_1d, as far as I know. @Sven's answer below is probably your best bet if you need to always preserve the type of the array. As it will always return a slice, the type should be preserved.
2

Here is a slightly more complex version that always returns a view into the original array (of course provided that you don't do any advanced indexing; this should be guaranteed by your specification of valid indices):

def get(a, item):
    if not isinstance(item, tuple):
        item = (item,)
    if len(item) == a.ndim and all(isinstance(x, int) for x in item):
        return a[item + (None,)]
    else:
        return a[item]

Comments

0

Apart from np.array(a[whatever])? Don't think there is a simpler/more idiomatic way than this.

1 Comment

Actually that doesn't do what the OP wants (e.g. have a look at the shape of the resulting array when the result of the slice is a scalar.)

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.