How to remove specific elements from a NumPy array?¶
To remove specific elements from a NumPy array, you can use boolean indexing to select only the elements you want to keep, and then create a new array from those elements.
Here's an example that removes all occurrences of a specific value (e.g., 0) from a NumPy array:
In [1]:
import numpy as np
# create an example array
a = np.array([1, 0, 2, 0, 3, 0, 4])
# use boolean indexing to select only the elements that are not 0
a = a[a != 0]
# print the result
print(a)
[1 2 3 4]
In [ ]:
Comments
Post a Comment