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.
Submitted by Pranit Sharma, on March 09, 2023

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

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).

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?

Python NumPy Programs »





Comments and Discussions!

Load comments ↻





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