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.

Deleting elements from arrays


To delete elements in your dataset, usenp.delete



Using np.delete

Deleting elements from 1D Arrays

Let's start with this array in x and delete the 2nd and 4th elements. To do so, we simply need to specify the positions in np.delete

Deleting elements from 2D Arrays

Now lets say we have a 2D array.  Removing elements will no longer be as easy as removing them from 1D arrays. If you remove just 1 element, the array will have improper dimensions. Hence, all that can be done is to remove entire columns or rows. 

Let's start with a new array y and delete the elements in the 2nd row.

Below, 0  and axis = 1 refers to the elements in the first column. Recall that axis defines whether you choose columns or rows. 

y = np.delete(y, 0, axis = 1)

Using the same array, let's try a different combination to delete elements from the second row. Here, 0  and axis = 0 refers to the elements in the first row.

y = np.delete(y, 0, axis = 0)

Video Guide


Remove the elements from the middle column of this array:

myArray = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7]])

Your codes should look like this:

[[1 3]
 [4 6]
 [9 7]]