Prepend element to numpy array

I just wrote some code that does this operation ~100,000 times, so I needed to figure out the fastest way to do this. I'm not an expert in code efficiency by any means, but I could figure some things out by using the %%timeit magic function in a jupyter notebook.

My findings:

np.concatenate(([number],array)) requires the least time. Let's call it 1x time.

np.asarray([number] + list(array)) comes in at ~2x.

np.r_[number,array] is ~4x.

np.insert(array,0,number) appears to be the worst option here at 8x.

I have no idea how this changes with the size of array (I used a shape (15,) array) and most of the options I suggested only work if you want to put the number at the beginning. However, since that's what the question is asking about, I figure this is a good place to make these comparisons.


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.