Wednesday, January 26, 2022

Removing Items from a NumPy Array

To delete an item from an array, you may use the delete() method. You need to pass the existing array and the index of the item to be deleted to the delete() method. The following script deletes an item at index 1 (second item) from the my_array array.

my_array = np.array(["Red", "Green", "Orange"])

print(my_array)

print("After deletion")

updated_array = np.delete(my_array, 1)

print(updated_array)

The output shows that the item at index 1, i.e., “Green,” is deleted. 

Output:

['Red' 'Green' 'Orange']

After deletion

['Red' 'Orange']

If you want to delete multiple items from an array, you can pass the item indexes in the form of a list to the delete() method. For example, the following script deletes the items at index 1 and 2 from the NumPy array named my_array.

my_array = np.array(["Red", "Green", "Orange"])

print(my_array)

print("After deletion")

updated_array = np.delete(my_array, [1,2])

print(updated_array)

Output:

['Red' 'Green' 'Orange']

After deletion

['Red']

You can delete a row or column from a 2-D array using the delete method. However, just as you did with the append() method for adding items, you need to specify whether you want to delete a row or column using the axis attribute.

The following script creates an integer array with four rows and five columns. Next, the delete() method is used to delete the row at index 1(second row). Notice here that to delete the array, the value of the axis attribute is set to 0.

integer_random = np.random.randint(1,11, size=(4, 5))

print(integer_random)

print("After deletion")

updated_array = np.delete(integer_random, 1, axis = 0)

print(updated_array)

The output shows that the second row is deleted from the input 2-D array.

Output:

[[ 2 3 3 3 4]

[ 1 7 6 7 10]

[ 7 1 6 6 8]

[ 3 7 8 10 7]]

After deletion

[[ 2 3 3 3 4]

[ 7 1 6 6 8]

[ 3 7 8 10 7]]

Finally, to delete a column, you can set the value of the axis attribute to 1, as shown below:

print(integer_random)

print("After deletion")

updated_array = np.delete(integer_random, 1, axis = 1)

print(updated_array)

The output shows all the rows from our two-dimensional NumPy array.

Output:

[[ 9 10 10 5 5]

[ 5 1 2 4 2]

[ 5 1 3 7 8]

[ 5 1 8 2 5]]

After deletion

[[ 9 10 5 5]

[ 5 2 4 2]

[ 5 3 7 8]

[ 5 8 2 5]]

Next we will talk about N-dimensional array object, or ndarray. Till we meet keep practicing and revising.

Share:

0 comments:

Post a Comment