NumPy Tutorial · NumPy Tutorial

NumPy Array Filter

Learn all about NumPy Array Filter in this comprehensive tutorial.

5 min read intermediate
  • Getting some elements out of an existing array and creating a new array out of them is called filtering.
  • In the example above we hard-coded the True and False values, but the common use is to create a filter array based on conditions.
  • The above example is quite a common task in NumPy and NumPy provides a nice way to tackle it.

Filtering Arrays

Getting some elements out of an existing array and creating a new array out of them is called filtering.

In NumPy, you filter an array using a boolean index list.

Note: A boolean index list is a list of booleans corresponding to indexes in the array.

If the value at an index is True that element is contained in the filtered array, if the value at that index is False that element is excluded from the filtered array.

python

The example above will return [41, 43], why?

Because the new array contains only the values where the filter array had the value True, in this case, index 0 and 2.

Creating the Filter Array

In the example above we hard-coded the True and False values, but the common use is to create a filter array based on conditions.

python
python

Creating Filter Directly From Array

The above example is quite a common task in NumPy and NumPy provides a nice way to tackle it.

We can directly substitute the array instead of the iterable variable in our condition and it will work just as we expect it to.

python
python

Module quiz

2 questions
1

Which of the following is true about NumPy Array Filter?

2

What is the most common pitfall when working with NumPy Array Filter?

Answer all questions to submit.