深度阅读

How to add/remove elements to a NumPy array

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

To add elements to a NumPy array, you can use the np.append() or np.concatenate() functions. Here’s an example of each:

import numpy as np

# add an element to the end of the array using np.append()
a = np.array([1, 2, 3])
a = np.append(a, 4)
print(a)  # [1 2 3 4]

# add an element to the end of the array using np.concatenate()
b = np.array([5, 6, 7])
b = np.concatenate((b, [8]))
print(b)  # [5 6 7 8]

To remove elements from a NumPy array, you can use the np.delete() function. Here’s an example:

import numpy as np

# remove an element from the array using np.delete()
c = np.array([1, 2, 3, 4])
c = np.delete(c, 2)   # remove the element at index 2
print(c)  # [1 2 4]

Note that both of these functions return a new array rather than modifying the original array in place. If you need to modify the original array in place, you can use slicing and indexing to modify individual elements or ranges of elements.

相关标签

博客作者

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