How To Filter Data In Python Without Pandas

In this tutorial, you will learn how to filter data in Python without using the popular library Pandas, which is commonly used to manipulate datasets.

Sometimes, you might want to filter data without relying on Pandas or other third-party libraries, especially in cases where you want to keep your project size small or have a limited capacity for library dependencies.

We will cover different ways to filter data in Python using native data structures, such as lists and dictionaries, and built-in functions, like lambda, filter, and more.

Filter Data using List Comprehension

One Pythonic way to filter data is by employing list comprehensions. List comprehensions allow you to create new lists from existing ones by applying an expression to each element. Let’s start a simple function to demonstrate this on a list of integers:

Now, let’s test the function with a sample input list:

The output will display the list of even numbers in the given data:

[0, 2, 4, 6, 8, 10]

Filter Data using Lambda and Filter Functions

Another popular method to filter data in Python is using lambda and filter built-in functions. The lambda function allows you to create anonymous functions, while the filter function applies a particular condition to the input iterable, such as a list or dictionary, and outputs the elements that satisfy the condition.

Here’s an example of how to use lambda and filter to filter out even numbers from a given list:

Now, let’s test the function again with the sample input list:

The output will also display the list of even numbers in the given data:

[0, 2, 4, 6, 8, 10]

Filter Data using Dictionary Comprehension

You can also filter data in Python using dictionaries and dictionary comprehensions. Dictionary comprehensions are similar to list comprehensions but are specifically meant for creating new dictionaries from existing ones, by applying an expression to each key-value pair in the dictionary.

In the following example, we will create a function that filters employee data using dictionary comprehension:

Now, let’s test the function with a given employee data set:

The output will display the filtered employee data with high salaries:

{'Alice': 60000, 'Bob': 55000, 'David': 65000}

Full Code:

Conclusion

In this tutorial, you’ve learned how to filter data in Python without using the Pandas library. We covered three different methods for data filtering using list comprehension, lambda and filter functions, and dictionary comprehension.

While Pandas is a powerful library for manipulating data, these native Python data structures and functions can be just as effective and simple for smaller tasks or when dependencies are limited.