# 從 NumPy 中的陣列中刪除元素

Vaibhav Vaibhav 2023年10月10日

## 使用 `numpy.delete()` 函式刪除元素

``````import numpy as np

myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
indexes = [3, 5, 7]
modifiedArray = np.delete(myArray, indexes)
print(modifiedArray)
``````

``````[ 1  2  3  5  7  9 10]
``````

``````import numpy as np

myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
indexes = [3, 5, 7, 34]
modifiedArray = np.delete(myArray, indexes)
print(modifiedArray)
``````

``````Traceback (most recent call last):
File "<string>", line 5, in <module>
File "<__array_function__ internals>", line 5, in delete
File "/path/to/library/numpy/lib/function_base.py", line 4480, in delete
keep[obj,] = False
IndexError: index 34 is out of bounds for axis 0 with size 10
``````

``````import numpy as np

myArray = np.array([[1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25]])
modifiedArray = np.delete(myArray, [1, 2], 1)
print(modifiedArray)
``````

``````[[ 1  4  5]
[11 14 15]
[21 24 25]]
``````

``````import numpy as np

myArray = np.array([[1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25]])
modifiedArray = np.delete(myArray, [1, 2], None)
print(modifiedArray)
``````

``````[ 1  4  5 11 12 13 14 15 21 22 23 24 25]
``````

## 使用 `numpy.setdiff1d()` 函式刪除元素

`setdiff1d()` 返回 `ar1` 中不在 `ar2` 中的唯一值。

``````import numpy as np

myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
indexes = [3, 5, 7]
modifiedArray = np.setdiff1d(myArray, indexes)
print(modifiedArray)
``````

``````[ 1  2  4  6  8  9 10]
``````

`numpy.delete()` 不同，這兩個陣列都是 NumPy 陣列，其中包含實際元素，但沒有索引。

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.