Skip to content
Related Articles

Related Articles

Improve Article
How to filter two-dimensional NumPy array based on condition ?
  • Last Updated : 05 Apr, 2021

In this article, we are going to see how to apply the filter by the given condition in NumPy two-dimensional array. We have to obtain the output of required elements i.e., whatever we want to filter the elements from the existing array or new array.

Here we are going to create a two-dimensional array in numpy.

Python3




import numpy as np
  
  
# 2-D Array also called as arrays 
# with rank 2
np_2d_arr = np.array([[1, 2, 3], [4, 5, 6]])
  
# View the 2-D Array A2
print(np_2d_arr)

Output:

[[1 2 3]
 [4 5 6]]

Now let see some example for applying the filter by the given condition in NumPy two-dimensional array.



Example 1: Using np.asarray() method

In this example, we are using the np.asarray() method which is explained below:

Syntax : numpy.asarray(arr, dtype=None, order=None)

Parameters :

  • arr : [array_like] Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
  • dtype : [data-type, optional] By default, the data-type is inferred from the input data.
  • order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ā€˜Cā€™.

Return : [ndarray] Array interpretation of arr. No copy is performed if the input is already ndarray with matching dtype and order. If arr is a subclass of ndarray, a base class ndarray is returned.

Here, we first create a numpy array and a filter with its values to be filtered. To filter we used this fltr in numpy.in1d() method and stored as its values in the original array that return True if condition fulfills.

Python3




import numpy as np
  
  
arr = np.asarray([[1, 'one'], [2, 'two'], [3, 'three'],
                  [4, 'four'], [5, 'five']])
  
fltr = np.asarray(['two', 'four'])
arr[np.in1d(arr[:, 1], fltr)]

Output:

array([['2', 'two'],
       ['4', 'four']], dtype='<U21')

Example 2: Using numpy.all() method

In this example, we are using the np.all() method which is explained below:

The numpy.all() function tests whether all array elements along the mentioned axis evaluate to True.



Syntax: numpy.all(array, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)

Parameters :

  • Array :[array_like]Input array or object whose elements, we need to test.
  • axis : [int or tuple of ints, optional]Axis along which array elements are evaluated.
  • out : [ndarray, optional]Output array with same dimensions as Input array, placed with result
  • keepdmis : [boolean, optional]If this is set to True.

Return : A new Boolean array as per ‘out’ parameter

Here, we first create a numpy array by using np.arrange() and reshape() methods. To filter we used conditions in the index place to be filtered. The np.all() method return True if all the values fulfills the condition. This return value maps with the original array to give the filtered values.

Python3




import numpy as np
  
  
a = np.arange(12).reshape((3, 4))
print(a[:, np.all(a < 10, axis = 0)])

Output:

[[0 1]
 [4 5]
 [8 9]]

Example 3: Using numpy.any() method

In this example, we are using the np.any() method which is explained below:

The numpy.any() function tests whether any array elements along the mentioned axis evaluate to True.
Syntax : numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)

Parameters :

  • array :[array_like]Input array or object whose elements, we need to test.
  • axis : [int or tuple of ints, optional]Axis along which array elements are evaluated.
  • out : [ndarray, optional]Output array with same dimensions as Input array, placed with result
  • keepdmis : [boolean, optional]If this is set to True.

Return : A new Boolean array as per ‘out’ parameter

Here, we first create a numpy array by using np.arrange() and reshape() methods. To filter we used conditions in the index place to be filtered. The np.any() method return true if any of the values fulfill the condition. This return value maps with the original array to give the filtered values.

Python3




import numpy as np
  
  
a = np.arange(12).reshape((3, 4))
print(a[:, np.any(a < 2, axis = 0)])

Output:

[[0 1]
 [4 5]
 [8 9]]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :