How to filter Pandas DataFrame by list values

Pandas-search

In this post, We are going to how to filter Pandas DataFrame by list values . We will learn this with the built-in iloc[],loc[], isin(),read_csv() function of the pandas dataframe.

1. iloc[] to filter Pandas dataframe by list values


iloc[] : It filters rows and columns by number( integer index/by position).Every row in the dataframe has a row number starting from 0 to the total number of rows and the column has a column number starting from 0 to the total number of columns. This number is used to filter the rows.

Python Program to filter dataframe by list values

import pandas as pd

 
Student_dict = {
    'Name': ['Jack', 'Rack', 'Max'],
    'Marks':[100,80,100],
    'Subj': ['Math', 'Math', 'Music']
}

dfobj = pd.DataFrame(Student_dict)

lst_of_indexes = [0,2]
rows = dfobj.iloc[lst_of_indexes, :]
print(rows)


Output

   Name  Marks   Subj
0  Jack    100   Math
2   Max    100  Music

2. isin() to filter dataframe by index in list


isin(): This method filters the dataframe by checking each element of the dataframe containing in given values or not. In this python program, we are checking if ‘Name’ columns contain the values in the list.

Python Program to filter dataframe by isin()

import pandas as pd

 
Student_dict = {
    'Name': ['Jack', 'Rack', 'Max'],
    'Marks':[100,80,100],
    'Subj': ['Math', 'Math', 'Music']
}

dfobj = pd.DataFrame(Student_dict)

lst_indexes = ['Rack','Jack']


rows = dfobj[dfobj['Name'].isin(lst_indexes)]
print(rows)

Output

  Name  Marks  Subj
0  Jack    100  Math
1  Rack     80  Math

3. loc[] to filter dataframe by index in list


In this Python program, we filter the dataframe that list contains the dataframe by using the loc[] function of the dataframe. It selects rows by label/index or select row by condition.

In this Python program, we are selecting the rows by a list of the index.

Python Program to filter dataframe by list of index

import pandas as pd

 
Student_dict = {
    'Name': ['Jack', 'Rack', 'Max'],
    'Marks':[100,80,100],
    'Subj': ['Math', 'Math', 'Music']
}

dfobj = pd.DataFrame(Student_dict)

lst_indexes = [0,2]

rows = dfobj.loc[dfobj.index[lst_indexes]]
print(rows)

Output

  Name  Marks   Subj
0  Jack    100   Math
2   Max    100  Music

4. Filter dataframe by list values using read_csv()


Sometimes instead of filtering row by index from a dataframe. We can filter the row by using the Pandas library read_CSV() method. This method creates a dataframe from a csv file. So while loading data rows can be skipped rows to filter the dataframe by list as we are doing in the below example.

Python Program to filter dataframe by list using read_csv()

import pandas as pd


lst_of_indexes = [1,2]
 
studf = pd.read_csv('student.csv',sep = ',',skiprows=lst_of_indexes)



print(studf)