Is this the best way to add an extra dimension to a numpy array in one line of code?

前端 未结 2 1277
情深已故
情深已故 2020-12-01 18:17

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, .

2条回答
  •  余生分开走
    2020-12-01 18:35

    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).

提交回复
热议问题