You can use a bool index array that you can produce using np.in1d.

You can index a np.ndarray along any axis you want using for example an array of bools indicating whether an element should be included. Since you want to index along axis=0, meaning you want to choose from the outest index, you need to have 1D np.array whose length is the number of rows. Each of its elements will indicate whether the row should be included.

A fast way to get this is to use np.in1d on the second column of a. You get all elements of that column by a[:, 1]. Now you have a 1D np.array whose elements should be checked against your filter. Thats what np.in1d is for.

So the complete code would look like:

import numpy as np

a = np.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']])
filter = np.asarray(['a','c'])
a[np.in1d(a[:, 1], filter)]

or in a longer form:

import numpy as np

a = np.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']])
filter = np.asarray(['a','c'])
mask = np.in1d(a[:, 1], filter)
a[mask]
Answer from jotasi on Stack Overflow
Top answer
1 of 4
7

You can use a bool index array that you can produce using np.in1d.

You can index a np.ndarray along any axis you want using for example an array of bools indicating whether an element should be included. Since you want to index along axis=0, meaning you want to choose from the outest index, you need to have 1D np.array whose length is the number of rows. Each of its elements will indicate whether the row should be included.

A fast way to get this is to use np.in1d on the second column of a. You get all elements of that column by a[:, 1]. Now you have a 1D np.array whose elements should be checked against your filter. Thats what np.in1d is for.

So the complete code would look like:

import numpy as np

a = np.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']])
filter = np.asarray(['a','c'])
a[np.in1d(a[:, 1], filter)]

or in a longer form:

import numpy as np

a = np.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']])
filter = np.asarray(['a','c'])
mask = np.in1d(a[:, 1], filter)
a[mask]
2 of 4
3

A somewhat elaborate pure numpy vectorized solution:

>>> import numpy
>>> a = numpy.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']])
>>> filter = numpy.array(['a','c'])
>>> a[(a[:,1,None] == filter[None,:]).any(axis=1)]
array([['2', 'a'],
       ['4', 'c']], 
      dtype='|S21')

None in the index creates a singleton dimension, therefore we can compare the column of a and the row of filter, and then reduce the resulting boolean array

>>> a[:,1,None] == filter[None,:]
array([[ True, False],
       [False, False],
       [False,  True],
       [False, False]], dtype=bool)

over the second dimension with any.

🌐
Python Guides
pythonguides.com › python-numpy-filter
How to Filter NumPy 2D Array by Condition in Python
May 16, 2025 - This approach keeps your 2D structure intact while masking values that don’t meet your condition. ... Python np.compress() function lets you filter along a specific axis based on a condition. import numpy as np # Website traffic data (visitors per day) for different sites (rows) across weeks (columns) traffic_data = np.array([ [1200, 1500, 1100, 1300], # Site A [500, 450, 550, 480], # Site B [2200, 2500, 2300, 2400], # Site C [850, 900, 830, 870] # Site D ]) # Filter to keep only high-traffic sites (>1000 visitors on average) row_condition = np.mean(traffic_data, axis=1) > 1000 high_traffic_sites = np.compress(row_condition, traffic_data, axis=0) print("High-traffic websites (>1000 daily visitors on average):") print(high_traffic_sites)
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-filter-two-dimensional-numpy-array-based-on-condition
How to filter two-dimensional NumPy array based on condition ? - GeeksforGeeks
July 23, 2025 - 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) ... Now let see some example for applying the filter by the given condition in NumPy two-dimensional array. ... 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.
🌐
Medium
mr-amit.medium.com › how-to-filter-data-in-numpy-79b6ca4eaff7
How to Filter Data in NumPy?. “Data is like gold — it’s valuable, but… | by It's Amit | Medium
March 6, 2025 - This might surprise you: You can filter an array using a list of values with just one function! NumPy’s np.isin() is your go-to tool for this.
🌐
Stack Overflow
stackoverflow.com › questions › 74812235 › how-to-filter-with-numpy-on-2d-array-using-np-where
python - How to filter with numpy on 2D array using np.where - Stack Overflow
So its hard for me to understand why the same syntax my_2d_array[:,1] is used to filter a whole column in python and to designate a single row of my 2D array for numpy where the condition is matched ... As documented, np.where with just one argument is just a call to nonzero, which finds the index(s) for the True values:
🌐
TutorialsPoint
tutorialspoint.com › numpy › numpy_filtering_arrays.htm
NumPy - Filtering Arrays
These conditions can be based on values or other criteria. Apply Conditions Across Dimensions − Use these conditions to index and select elements. For multi-dimensional arrays, you may need to handle conditions for specific dimensions or apply the condition across all dimensions. Consider a 2D array where we want to filter out rows based on a condition applied to elements in a specific column − · import numpy as np # Create a 2D NumPy array array = np.array([[10, 20, 30], [15, 25, 35], [20, 30, 40]]) # Define a condition for filtering # Select rows where the value in the second column is greater than 25 condition = array[:, 1] > 25 # Use the condition to filter the array filtered_array = array[condition] print("Original Array:\n", array) print("Condition (values in second column > 25):", condition) print("Filtered Array:\n", filtered_array)
Find elsewhere
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_filter.asp
NumPy Filter Array
In NumPy, you filter an array using a boolean index list. 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 ...
🌐
Dataquest
support.dataquest.io › en › articles › 812-filter-data-like-a-pro-with-this-simple-numpy-trick
Filter Data Like a Pro with This Simple NumPy Trick | DATAQUEST
May 19, 2026 - Searching for patterns or anomalies in big datasets can be tricky, but NumPy's Boolean indexing makes it simple. With this powerful technique, you can filter data intuitively using conditions—no loops required. Whether you're working with 1D or 2D arrays, Boolean indexing helps you extract exactly what you need in just a few lines of code.
🌐
Statology
statology.org › home › how to filter a numpy array (4 examples)
How to Filter a NumPy Array (4 Examples)
July 9, 2022 - #filter for values less than 5 or greater than 9 my_array[(my_array < 5) | (my_array > 9)] array([ 1, 2, 2, 3, 10, 12, 14]) This filter returns the values in the NumPy array that are less than 5 or greater than 9.
🌐
Hyperskill
hyperskill.org › university › numpy › numpy-array-filter
NumPy Array Filter
August 30, 2024 - The main advantage of using filters in NumPy arrays is the ability to carry out efficient operations on the entire dataset at once. This is accomplished by creating a boolean index list, where each element corresponds to a value in the array. The boolean values indicate whether a particular element should be included in the filtered array.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.where.html
numpy.where — NumPy v2.5 Manual
>>> x, y = np.ogrid[:3, :4] >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast array([[10, 0, 0, 0], [10, 11, 1, 1], [10, 11, 12, 2]])