6

numpy provides three handy routines to turn an array into at least a 1D, 2D, or 3D array, e.g. through numpy.atleast_3d

I need the equivalent for one more dimension: atleast_4d. I can think of various ways using nested if statements but I was wondering whether there is a more efficient and faster method of returning the array in question. In you answer, I would be interested to see an estimate (O(n)) of the speed of execution if you can.

3
  • Where should the 4th dimension go when it is added? As another trailing dimension, or as another leading dimension? Commented Apr 11, 2013 at 5:24
  • @talonmies Trailing is preferred Commented Apr 11, 2013 at 5:24
  • 2
    The execution speed is O(1) whatever the method, not O(n). Commented Apr 11, 2013 at 8:50

2 Answers 2

10

The np.array method has an optional ndmin keyword argument that:

Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.

If you also set copy=False you should get close to what you are after.


As a do-it-yourself alternative, if you want extra dimensions trailing rather than leading:

arr.shape += (1,) * (4 - arr.ndim)
Sign up to request clarification or add additional context in comments.

1 Comment

Your do-it-yourself approach is pretty. It took me a while to decode though. For the record: (1,) * (4 - arr.ndim) creates a tuple of ones. The tuple is either empty if arr.ndim is larger than 4 or of the appropriate length. Those dimension just get tagged on to the array. Beautiful.
1

Why couldn't it just be something as simple as this:

import numpy as np
def atleast_4d(x):
    if x.ndim < 4:
        y = np.expand_dims(np.atleast_3d(x), axis=3)
    else:
        y = x

    return y

ie. if the number of dimensions is less than four, call atleast_3d and append an extra dimension on the end, otherwise just return the array unchanged.

2 Comments

Just to clarify: expand_dims -> np.expand_dims
Also, needs a colon on the else; else => else:.

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.