29

If k is an numpy array of an arbitrary shape, so k.shape = (s1, s2, s3, ..., sn), and I want to reshape it so that k.shape becomes (s1, s2, ..., sn, 1), is this the best way to do it in one line?

k.reshape(*(list(k.shape) + [1])
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
qAp
  • 1,139
  • 2
  • 12
  • 26

2 Answers2

42

It's easier like this:

k.reshape(k.shape + (1,))

But if all you want is to add an empty dimension at the end, you should use numpy.newaxis:

import numpy as np
k = k[..., np.newaxis]

or

k = k[..., None]

(See the documentation on slicing).

tiago
  • 22,602
  • 12
  • 72
  • 88
5

You can use numpy.expand_dims

In [4]: import numpy as np                                                          

In [5]: a = [1,2,3,4]                                                                              

In [6]: np.expand_dims(a, axis=1)                                                                  
Out[6]: 
array([[1],
       [2],
       [3],
       [4]])
Akavall
  • 82,592
  • 51
  • 207
  • 251