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:

Image for post
Image for post
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)
Image for post
Image for post

What is axis in numpy.insert actually?

Here the original array is a matrix with two dimensions:

Image for post
Image for post
  • 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
Image for post
Image for post
Image for post
Image for post

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.
numpy.insert(arr, obj, values, axis)
Image for post
Image for post
print("axis=0")
x= np.insert(a, 2, [40,70], axis=0)
print(x)
Image for post
Image for post
x= np.insert(a, 2, [40,70])
print(x)
axis=null
[ 1 11 40 70 2 22 3 33]
x = np.c_[np.ones((100,1)),x]

Written by

Web geek, Self-taught full-stack web developer, Learning Python, Laravel, Vuejs, UX/UI design, Nuclear Physicist PhD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store