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

Published on Aug. 22, 2023, 12:16 p.m.

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.

Tags: