How to use pandas In Python
In this method we first initializes a list named test_list and a boolean list named bool_list. It then creates a pandas series from the original list using pd.Series() function and filters the series using boolean indexing with bool_list. The resulting filtered series is then converted back to a list using the tolist() function, and the final filtered list is printed using the print() function.
Python3
import pandas as pd # initializing list test_list = [ 1 , 2 , 3 , 4 ] # printing list print ( "The original list : " + str (test_list)) # initializing Boolean list bool_list = [ True , False , True , False ] # printing boolean list print ( "The bool list is : " + str (bool_list)) # create a pandas series from the original list series = pd.Series(test_list) # filter the series by the boolean list filtered_series = series[bool_list] # convert the filtered series back to a list res = filtered_series.tolist() # Printing result print ( "List after filtering is : " + str (res)) |
Output:
The original list : [1, 2, 3, 4] The bool list is : [True, False, True, False] List after filtering is : [1, 3]
Time complexity: O(n), where n is the length of the original list
Auxiliary Space: O(n), where n is the length of the original list
Python | Filter list by Boolean list
Sometimes, while working with a Python list, we can have a problem in which we have to filter a list. This can sometimes, come with variations. One such variation can be filtered by the use of a Boolean list. Let’s discuss a way in which this task can be done.
Contact Us