Mastering Array Manipulation: A Deep Dive into the delete() Method

Understanding the delete() Syntax

The delete() method takes four arguments: the array to modify, the indices at which values are deleted, the axis along which the values are deleted (optional), and the obj parameter. By default, the axis is set to None, and the array is flattened.

delete(arr, indices, axis=None, obj)

Deleting Array Elements with Ease

Let’s dive into some examples to see the delete() method in action.

Deleting a Single Element

In our first example, we’ll delete a single element at a given index.

arr = [1, 2, 3, 4, 5]
delete(arr, 1)
print(arr)  # Output: [1, 3, 4, 5]

Deleting Multiple Elements

But what if we want to delete multiple elements at different indices?

arr = [1, 2, 3, 4, 5]
delete(arr, [1, 2])
print(arr)  # Output: [1, 4, 5]

Working with 2-D Arrays

The delete() method isn’t limited to 1-D arrays. We can also use it to delete elements from 2-D arrays at any index.

arr = [[1, 2, 3], [4, 5, 6]]
delete(arr, 1, axis=0)
print(arr)  # Output: [[1, 2, 3]]

Additionally, we can delete entire rows or columns by specifying the axis parameter.

  • If axis = 0, a row is deleted.
  • If axis = 1, a column is deleted.
arr = [[1, 2, 3], [4, 5, 6]]
delete(arr, 1, axis=1)
print(arr)  # Output: [[1, 3], [4, 6]]

Deleting Multiple Elements from a 2-D Array

arr = [[1, 2, 3], [4, 5, 6]]
delete(arr, [1, 2], axis=1)
print(arr)  # Output: [[1], [4]]

Conditional Deletion

But what if we want to delete elements based on specific conditions?

arr = [1, 2, 3, 4, 5]
delete(arr, lambda x: x % 2 == 0)
print(arr)  # Output: [1, 3, 5]

With the delete() method, you now have the power to efficiently manipulate and modify your arrays with precision and flexibility.

Leave a Reply