This tutorial will discuss about unique ways to randomly remove elements from a numpy array.
Suppose we have an array of numbers,
numbers = np.array([34, 35, 78, 61, 56, 71, 90, 91])
For this, we will create an array of random indices from this array of size N. Like this,
# Use the `random.choice()` function to # randomly select the indices of the elements to remove indicesToRemove = np.random.choice( numbers.size, num, replace=False)
Then we will pass this array of random index positions into the numpy.delete() function, along with the numpy array. Like this,
# Update NumPy Array without the specified elements numbers = np.delete(numbers, indicesToRemove)
It will delete all the elements at the given index positions. This way we can delete the random values from a number array.
Frequently Asked:
In the belowe example, we will delete 2 random values from a NumPy Array.
Let’s see the complete example,
import numpy as np # Create a NumPy Array numbers = np.array([34, 35, 78, 61, 56, 71, 90, 91]) # Define the number of # elements to remove num = 2 # Use the `random.choice` function to # randomly select the indices of the elements to remove indicesToRemove = np.random.choice( numbers.size, num, replace=False) # Update NumPy Array without the specified elements numbers = np.delete(numbers, indicesToRemove) # Print the numpy array print(numbers)
Output
[35 78 61 56 71 90]
Summary
We learned how to delete N random values from a NumPy Array in Python.
Latest Video Tutorials