Home »
Python »
Python Programs
Prepend element to numpy array
Learn, how to prepend element to numpy array in Python?
By Pranit Sharma Last updated : October 10, 2023
NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.
Problem statement
Suppose we are given a NumPy array and we need to insert some element at the beginning of this array.
Prepending element to numpy array
For this purpose, we will use numpy.insert() method. This method inserts values along the given axis before the given indices.
If the type of values is different from that of arr, values are converted to the type of arr.Values.
It takes an array as an argument in which the element has to be inserted and it takes an argument obj which is the object that defines the index or indices before which values are inserted. It returns a copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned. If the axis is None, the output is a flattened array.
Let us understand with the help of an example,
Python program to prepend element to numpy array
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.array([[1, 1], [2, 2], [3, 3]])
# Display original array
print("Original array:\n",arr,"\n")
# Inserting 5 at 1st position
arr = np.insert(arr, 1, 5)
# Display result
print("Result:\n",arr)
Output
The output of the above program is:
Python NumPy Programs »