NumPy provides various methods to filter arrays based on different criteria. Filtering arrays can be done in various ways e.g selection of elements based on a condition, excluding some elements from an array, filtering unique elements of an array, etc. Let’s discuss these methods in detail.
Filtering an array based on a condition
The simplest way to filter an array is by selecting only those elements that satisfy a specified condition. It can be done using the where
method of NumPy. Let’s say we want to select only those elements from an array which are greater than 5. We can achieve this as follows:
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # Select elements greater than 5 newarr = np.where(arr > 5) print(newarr)
The output of the above code will be:
(array([5, 6, 7, 8, 9]),)
The returned array contains the indexes of the elements that satisfy the condition. We can also use the returned indexes to get the actual values from the original array, as shown below:
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # Select elements greater than 5 newarr = arr[np.where(arr > 5)] print(newarr)
The output of the above code will be:
[ 6 7 8 9 10]
Filtering unique elements of an array
Sometimes, we may want to filter out all the duplicate elements from an array. We can achieve this using the unique
method of NumPy. The unique
method returns the sorted unique elements of an array. Let’s see an example:
import numpy as np arr = np.array([1, 2, 3, 4, 2, 4, 6, 7, 4]) newarr = np.unique(arr) print(newarr)
The output of the above code will be:
[1 2 3 4 6 7]
Filtering an array excluding some elements
Sometimes, we may want to filter out some elements from an array based on a condition. We can achieve this using the delete
method of NumPy. The delete
method returns a new array with the specified subarray deleted. Let’s see an example:
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # Delete elements greater than 5 newarr = np.delete(arr, np.where(arr > 5)) print(newarr)
The output of the above code will be:
[1 2 3 4 5]
Conclusion
In this tutorial, we learned about different methods to filter NumPy arrays based on various conditions. We learned how to select elements based on a condition, filter unique elements, and exclude some elements from an array. NumPy provides many such useful methods to filter and manipulate arrays, making it a powerful library for scientific computing in Python.