NumPy Delete: Remove Elements from Arrays

One can remove specified elements using the delete() function in the NumPy library. The usage of the delete() function is as follows:

numpy.delete(arr, obj, axis=None)

In this case, arr is the array to be operated on, obj is the index or slice object of the element to be deleted, and axis is the axis to delete. If axis is not specified, the array will be flattened into a one-dimensional array, and then the specified element will be deleted.

The following is an example demonstrating how to use the delete() function to remove a specified element:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
new_arr = np.delete(arr, 2)  # 删除索引为2的元素
print(new_arr)  # 输出: [1 2 4 5]

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
new_arr = np.delete(arr, 1, axis=0)  # 删除第1行
print(new_arr)
# 输出:
# [[1 2 3]
#  [7 8 9]]

new_arr = np.delete(arr, 1, axis=1)  # 删除第1列
print(new_arr)
# 输出:
# [[1 3]
#  [4 6]
#  [7 9]]

In the examples above, the np.delete() function removed specified elements from both a one-dimensional array and a two-dimensional array.

bannerAds