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

import numpy as np
a = np.array([[1, 11], [2, 22], [3, 33]])
print('Original array:')
print(a)
print()
print("axis=1")
x= np.insert(a, 0, 6, axis=1)
print(x)
print()
print("axis=0")
x= np.insert(a, 2, 5, axis=0)
print(x)

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.

Attention:

  • 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

and

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:

numpy.insert(arr, obj, values, axis)

where:

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:

print("axis=0")
x= np.insert(a, 2, [40,70], axis=0)
print(x)

the results will be:

Let’s try numpy.insert without passing axis!

x= np.insert(a, 2, [40,70])
print(x)

results:

axis=null
[ 1 11 40 70 2 22 3 33]

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

An alternative solution is using:

x = np.c_[np.ones((100,1)),x]

Posting daily about Python, Laravel, Livewire, Nuclear Physicist PhD