Expand numpy array dimensions to a given shape

Viewed 123

Is there a way to reshape an array into a certain shape padding missing dimensions?

Let's say, we have an array x

x = np.arange(10) 

Now we want to reshape it to (1, 1, 1, 10, 1). We can do:

x = x.reshape((1, 1, 1, 10, 1)) 

or

x = x[None, None, None, x.shape[0], None]

But if the number and position of padding dimensions vary, this becomes quite inconvenient. Is there a better way?

2 Answers

You can construct the new shape programatically:

pre_pad, post_pad = 5,2
new_shape = tuple([1]*pre_pad) + x.shape + tuple([1]*post_pad)

y = x.reshape(new_shape)

print(y.shape)
# (1, 1, 1, 1, 1, 10, 1, 1)

You could use np.pad, which gives you a lot of control:

x = np.arange(10)

new_shape = np.pad([x.shape[0]],       # the thing to pad, in this case, [10]
                   (3,1),              # padding on (left, right)
                   'constant',    
                   constant_values=1)  # could specify L/R instead, e.g. (2,3)

y = x.reshape(new_shape)
y.shape
# (1, 1, 1, 10, 1)
Related