numpy.insert python prepend element to numpy array with axis parameter

numpy has an insert function that's accesible via numpy.insert referto its document.

Let’s have a look at this code in Jupyter python:

You can try this code

The output will be:

What is axis in numpy.insert actually?

Here the original array is a matrix with two dimensions:

In this case the axis=0 means we want to insert a row and if axis=1 it means we want to insert a column.

The argument axis= specifies that the insertion should happen as a column or row.


  • row index 0 = [1 11]
  • row index 1 = [2 22]
  • row index 2 = [3 33]
  • column index 0 = 1 2 3 sorry for this presentation, you understand that it is a column
  • column index 1 = 11 22 33

Now lets look at the numpy.insert parameters command again


Explaining parameters of python numpy.insert:

  • As you see the first argument a specifies the object (original array) to be inserted into.
  • The second argument specifies where we want to insert. ( before which index of original array, regarding we want to insert as column or row )
  • The third argument specifies what is to be inserted.

In General form numpy.insert has this form:


arr : Input array

obj : The index before which insertion is to be made

values : The array of values to be inserted. It can be also one number or array of numbers

axis : The axis along which to insert. If not given, the input array is flattened

Let’s try when values in the paramenters is an array like:

This code:

the results will be:

Let’s try numpy.insert without passing axis!


As you see if axis is not given, the input array is flattened.

An alternative solution is using:

Posting daily about Python, Nuclear Physicist PhD