Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: NP.10 Deleting elements from arrays

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

Deleting elements from arrays

np.delete()

To delete elements in your dataset, usenp.delete

Syntax

np.delete(ndarray,elements,axis) 

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)

Exercises

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]]

Video Guide