In this article, we will discuss how to use numpy.insert() to insert elements in between other elements in a numpy array.
Table of Contents
- Overview of numpy.insert()
- Insert an element into a NumPy array at a given index position.
- Insert multiple elements into a NumPy array at the given index.
- Insert multiple elements at multiple indices in a NumPy array.
- Insert a row into a 2D Numpy array.
- Insert a column into a 2D Numpy array.
Overview of numpy.insert()
In Python, Numpy Library provides a function to insert elements in a numpy array,
numpy.insert(arr, index, values, axis=None)
Arguments:
- arr: array_like object
- The input array
- index: int, slice or sequence of ints
- The index position or multiple indices before which values needs to be inserted.
- values: array_like object
- Values that need to be inserted into array arr.
- If the type of the values provided are different from that of arr, then values are converted to the type of arr.
- Values that need to be inserted into array arr.
- axis: int, optional
- Then axis along which values need to be inserted.
- If axis is None, then arr is flattened first and then values are inserted at given position.
- If axis is 0, then values will be inserted row wise in array arr.
- If axis is 0, then values will be inserted column wise in array arr.
- Then axis along which values need to be inserted.
Returns
- out: ndarray
- A copy of arr with given values inserted ar given indices.
- If axis is None, then it returns a flattened array.
- If axis is 1, then insert column-wise.
- If axis is 0, then insert row-wise.
- It does not modifies the original array, instead it returns a copy of given array with inserted values.
- A copy of arr with given values inserted ar given indices.
Let’s understand with some examples,
Insert an element into a NumPy array at a given index position
Suppose we have a NumPy Array of integers and we want to insert an element 10 ath the index position 2. For that we will call the insert() with array, index position and element to be inserted,
import numpy as np # Create a Numpy Array of integers arr = np.array([11, 18, 6, 7, 1]) # Insert an element 10 at index position 2 new_arr = np.insert(arr, 2, 10) print('New Array: ', new_arr) print('Original Array: ', arr)
Output:
New Array: [11 18 10 6 7 1] Original Array: [11 18 6 7 1]
It returned a new array with element 10 inserted at the index position 2. The original array is not modified.
Insert multiple elements into a NumPy array at the given index
To insert multiple elements in a numpy array, pass the elements as a sequence along with the index position, to the insert() function. For example,
import numpy as np # Create a Numpy Array of integers arr = np.array([11, 18, 6, 7, 1]) # Insert three element at index position 2 new_arr = np.insert(arr, 2, (5, 5, 5)) print('New Array: ', new_arr)
Output:
New Array: [11 18 5 5 5 6 7 1]
It inserted three elements i.e. 5, 5, & 5 at the index position 2.
Insert multiple elements at multiple indices in a NumPy array
In this previous example, we inserted three elements at a given index position. But what if we want to insert three different elements at three different index position like,
- Insert 22 at index 1.
- Insert 33 at index 2.
- Insert 44 at index 3.
For this we need to pass the index positions as a sequence along with values sequence,
import numpy as np # Create a Numpy Array of integers arr = np.array([11, 18, 6, 7, 1]) # Insert three element index position 1, 2 and 3 new_arr = np.insert(arr, (1,2,3), (22, 33, 44)) print('New Array: ', new_arr)
Output:
New Array: [11 22 18 33 6 44 7 1]
It inserted three elements and three different places in the numpy array.
Insert a row into a 2D Numpy array
To insert a row in 2D Numpy Array we need to pass the axis as 0 and the values as a sequence. For example, let’s try to insert a row at index 1 in a 2D Numpy Array,
import numpy as np # Create 2D Numpy array of hard coded numbers arr = np.array([[1, 2, 3], [5, 6, 7], [3, 3, 3]]) # Insert a row at index 1 new_arr = np.insert(arr, 1, (5, 5, 5), axis=0) print(new_arr)
Output:
[[1 2 3] [5 5 5] [5 6 7] [3 3 3]]
It inserted the row at index 1.
We passed the row values as sequence, but you can also pass the values in different shape. If values are of different shape, then it will make them of required shape. For example,
import numpy as np # Create 2D Numpy array of hard coded numbers arr = np.array([[1, 2, 3], [5, 6, 7], [3, 3, 3]]) # Insert a row at index 1 new_arr = np.insert(arr, 1, 5, axis=0) print(new_arr)
Output:
[[1 2 3] [5 5 5] [5 6 7] [3 3 3]]
It inserted the row at index 1.
Insert a column into a 2D Numpy array
To insert a column in 2D Numpy Array we need to pass the axis as 1 and the values as a sequence. For example, let’s try to insert a column at index 1 in a 2D Numpy Array,
import numpy as np # Create 2D Numpy array of hard coded numbers arr = np.array([[1, 2, 3], [5, 6, 7], [3, 3, 3]]) # Insert a column at index 1 new_arr = np.insert(arr, 1, (5, 5, 5), axis=1) print(new_arr)
Output:
[[1 5 2 3] [5 5 6 7] [3 5 3 3]]
It inserted the column at index 1.
We passed the column values as sequence, but you can also pass the values in different shape. If values are of different shape, then it will make them of required shape. For example,
import numpy as np # Create 2D Numpy array of hard coded numbers arr = np.array([[1, 2, 3], [5, 6, 7], [3, 3, 3]]) # Insert a column at index 1 new_arr = np.insert(arr, 1, 5, axis=1) print(new_arr)
Output:
[[1 5 2 3] [5 5 6 7] [3 5 3 3]]
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.