Skip to Main Content

Python for Basic Data Analysis

Start your data science journey with Python. Learn practical Python programming skills for basic data manipulation and analysis.

Inserting elements into arrays

np.insert

Other than np.append, we can also use np.insert to add elements to arrays. np.insert will insert elements right before a specified index. 

Syntax

np.insert(ndarray, index, elements,axis)

np.append only adds elements to the last row/column while np.insert lets you add elements in a specific spot.

Adding elements using np.insert

Insert elements to 1D arrays

Let's begin with this array:

x = np.array([1,2,3,4])


Let's add 11,12 and 13 between the 2nd and 3rd elements. First, we first add square brackets around the numbers to be added. Next, we specify the index 2, to insert these numbers before the third element.
 


Insert elements to a row in 2D arrays

To work with 2-D arrays, we cannot simply add a random number of elements. If we are adding elements to a row, the row size must match. Likewise for columns.

Let's use a new array

y = np.array([[1,2],[3,4]])

 

Let's insert 11 and 12 between the 1st and 2nd rows. To do so, we should specify the row we would like to add, create a list for the new elements and specify the axis:

np.insert(y,1,[11,12],axis = 0)

 

Insert elements in a column to 2D arrays

Let's now insert elements to a new column.

You can add the same element in an entire column without having to create a list. You only need to indicate the element. This means, instead of typing in [11, 11], we only need to type 11.

y = np.insert(y,2,11,axis = 1) 

Video Guide

Exercises

1. Add 1 column of 1 to this array: myArray = np.zeros((2,2))

2. Add 2 rows of 2 to the answer from part 1

3. Remove the last column

4. Remove the last row