How to add/remove elements to a NumPy array

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

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.

Tags: