Search code examples
pythonnumpyinsert

Prepend element to numpy array


I have the following numpy array

import numpy as np

X = np.array([[5.], [4.], [3.], [2.], [1.]])

I want to insert [6.] at the beginning. I've tried:

X = X.insert(X, 0)

how do I insert into X?


Solution

  • numpy has an insert function that's accesible via np.insert with documentation.

    You'll want to use it in this case like so:

    X = np.insert(X, 0, 6., axis=0)
    

    the first argument X specifies the object to be inserted into.

    The second argument 0 specifies where.

    The third argument 6. specifies what is to be inserted.

    The fourth argument axis=0 specifies that the insertion should happen at position 0 for every column. We could've chosen rows but your X is a columns vector, so I figured we'd stay consistent.