3

Is there a way to add a variable number of singleton dimensions to a numpy array? I want something like atleast_2d but for an arbitrary number of dimensions. expand_dims comes up a lot, but only adds a single dimension.

The only way I know to do this is to compute the shape first and apply it, i.e.

import numpy as np

def atleast_kd(array, k):
    array = np.asarray(array)
    new_shape = array.shape + (1,) * (k - array.ndim)
    return array.reshape(new_shape)
2
  • 1
    Looks good. That's just a variant on what expand_dims does: a.reshape(shape[:axis] + (1,) + shape[axis:]) Commented Feb 28, 2017 at 18:57
  • @hpaulj I should have looked at the source. This solution seems more elegant given that expand_dims doesn't do anything better. Commented Feb 28, 2017 at 19:07

1 Answer 1

1

A more elegant way to do this is np.broadcast_to. For example:

a = np.random.rand(2,2)
k = # number_extra dimensions
b = np.broadcast_to(a, (1,) * k + a.shape)

This will add the dimensions to the beginning of b. To get the exact same behavior as the given function, you can use np.moveaxis.

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

1 Comment

This works, but broadcast_to will do other things if you're not careful so it doesn't seem like the appropriate method, granted, so will reshape, so :/. It also doesn't fix the main issue of having to compute the "new shape".

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.