深度阅读

How to add or remove elements in a NumPy array in Python

作者
作者
2023年08月22日
更新时间
13.11 分钟
阅读时间
0
阅读量

To add or remove elements in a NumPy array in Python, you can use various methods and functions provided by the NumPy library. Here are some examples:

Adding elements:

import numpy as np

# create a NumPy array
arr = np.array([1, 2, 3])

# append an element to the end of the array
arr = np.append(arr, 4)

# insert an element at a specific index
arr = np.insert(arr, 1, 5)

print(arr)  # [1, 5, 2, 3, 4]

In this example, we create a 1-dimensional NumPy array and then use the np.append() method to append an element to the end of the array. We then use the np.insert() method to insert a new element at index 1.

Removing elements:

import numpy as np

# create a NumPy array
arr = np.array([1, 2, 3, 4, 5])

# remove an element at a specific index
arr = np.delete(arr, 2)

print(arr)  # [1, 2, 4, 5]

In this example, we create a 1-dimensional NumPy array and then use the np.delete() method to remove the element at index 2.

Note that NumPy arrays are immutable, so adding or removing elements actually creates a new array object. Therefore, it is best to only use these methods and functions when you need to modify the size of an array. In cases where you only need to modify the values of an array, you can use indexing and slicing to directly modify the array elements.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。