How to insert a row at a specific location in a 2d array in NumPy?

Given a 2D NumPy array, we have to insert a row at a specific location in it.
By Pranit Sharma Last updated : December 26, 2023

Problem statement

Suppose that we are given a 2D NumPy array like [[2,2],[2,2]] and we need to insert a row at a specific location in this array (say after 1st row).

NumPy: Inserting a row at a specific location in 2D array

To insert a row at a specific location, we can simply use numpy.insert() function. We will first create another numpy 1D array (the row that needs to be inserted) and pass this array at index 1 (so that it is inserted after index 1).

Let us understand with the help of an example,

Python code to insert a row at a specific location in a 2d array in NumPy

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[2,2],[2,2]])

# Display Original array
print("Original array:\n",arr,"\n\n")

# Creating another array
arr2 = np.array([1,1])

# Inserting arr2 after 1st row in arr
res = np.insert(arr,1,arr2,0)

# Display result
print("Result:\n",res)

Output

Example: How to insert a row at a specific location in a 2d array in NumPy?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.