Filter dataframe based on index value

Given a pandas dataframe, we have to filter dataframe based on index value. By Pranit Sharma Last updated : September 29, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose, we are given a DataFrame with multiple columns, this DataFrame has custom indices that is it has some specific index value for each row.

We are also given a list of items, we need to check whether our indices of DataFrame lie inside this list of items or not.

Filtering dataframe based on index value

We will check this by accessing all the indices one by one by using df.index method which will return all the indices, for each index we will apply isin() method to check whether this value is present in the list which we will pass inside isin() method as an argument.

Let us understand with the help of an example,

Python code to filter dataframe based on index value

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'State':['MP','RAJ','GUJ','WB','MH','TN'],
    'Capital':['BHOPAL','JAIPUR','GANDHINAGAR','KOLKATA','MUMBAI','CHENNAI'],
    'River':['NARMADA','LUNI','SABARMATI','HOOGLY','GODAVARI','PERIYAR'],
    'Direction':['Centre','WEST','WEST','EAST','SOUTH_WEST','SOUTH']
}

# Creating DataFrame
df = pd.DataFrame(d,index=[10,2,30,4,50,6])

# Display the DataFrame
print("Original DataFrame:\n",df,"\n")

# Creating a list of indices
l = [10,2,6,50,100,23,54,32,87,65,79]

# Filtering dataframe
result = df[df.index.isin(l)]

# Display modified DataFrame
print("Modified DataFrame:\n",result)

Output

The output of the above program is:

Example: Filter dataframe based on index value

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.