Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
Label-based indexing to the Pandas DataFrame
Next article icon

Filter Pandas DataFrame Based on Index

Last Updated : 23 Mar, 2022
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In this article, we are going to see how to filter Pandas Dataframe based on index. We can filter Dataframe based on indexes with the help of filter(). This method is used to Subset rows or columns of the Dataframe according to labels in the specified index. We can use the below syntax to filter Dataframe based on index.

Syntax: DataFrame.filter ( items=None, like=None, regex=None, axis=None )

Parameters:

  • items : List of info axis to restrict to (must not all be present).
  • like : Keep info axis where “arg in col == True”
  • regex : Keep info axis with re.search(regex, col) == True
  • axis : The axis to filter on. By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame

Returns : This method is return same type of object as input object.

Example 1:

The following program is to understand how to filter Dataframe based on numeric value indexes.

Python
# import pandas
import pandas as pd

# define data
data = {"Name": ["Mukul", "Suraj", "Rohit",
                 "Rahul", "Mohit", "Nishu",
                 "Rishi", "Manoj", "Mukesh", 
                 "Rohan"],
        "Age": [22, 23, 25, 21, 27, 24, 26,
                23, 21, 27],
        "Qualification": ["BBA", "BCA", "BBA", 
                          "BBA", "MBA", "BCA",
                          "MBA", "BBA", "BCA", 
                          "MBA"]
        }

# define dataframe
df = pd.DataFrame(data, columns=['Name', 'Age', 'Qualification'])

# display original dataframe
print("\n Original Dataframe \n", df)

# filter 5 index value
df_1 = df.filter(items=[5], axis=0)

# display result
print("\n Display only 5 index value \n", df_1)

# filter only 5 and 8  index value
df_2 = df.filter(items=[5, 8], axis=0)

# display result
print("\n Display only 5 and 8 index value \n", df_2)

Output:

Example 2:

The following program is to know how to filter Dataframe based on non-numeric value indexes.

Python
# import pandas
import pandas as pd

# define data
data = {"Name": ["Mukul", "Suraj", "Rohit",
                 "Rahul", "Mohit"],
        "Age": [22, 23, 25, 21, 27],
        "Qualification": ["BBA", "BCA", "BBA",
                          "BBA", "MBA"]
        }

# define dataframe
df = pd.DataFrame(data, columns=['Name', 'Age', 'Qualification'], index=[
                  'Person_A', 'Person_B', 'Person_C', 'Person_D', 'Person_E'])

# display original dataframe
print("\n Original Dataframe \n", df)

# filter Person_B index value
df_1 = df.filter(items=['Person_B'], axis=0)

# display result
print("\n Display only Person_B index value \n", df_1)

# filter only Person_B and Person_D index value
df_2 = df.filter(items=['Person_B', 'Person_D'], axis=0)

# display result
print("\n Display Person_B and Person_D index value \n", df_2)

Output:

Example 3:

The following program is to understand how to filter Dataframe for indexes that contain a specific string.

Python
# import pandas
import pandas as pd

# define data
data = {"Name": ["Mukul", "Suraj", "Rohit", 
                 "Rahul", "Mohit"],
        "Age": [22, 23, 25, 21, 27],
        "Qualification": ["BBA", "BCA", "BBA", 
                          "BBA", "MBA"]
        }

# define dataframe
df = pd.DataFrame(data, columns=['Name', 'Age', 'Qualification'], index=[
                  'Person_A', 'Person_B', 'Person_AB', 'Person_c', 'Person_AC'])

# display original dataframe
print("\n Original Dataframe \n", df)

# filter index that contain Person_A string.
df_1 = df.filter(like='Person_A', axis=0)

# display result
print("\n display index that contain Person_A string \n", df_1)

Output

Example 4:

The following program is to know how to filter Dataframe for indexes that contain a specific character.

Python
# import pandas
import pandas as pd

# define data
data = {"Name": ["Mukul", "Suraj", "Rohit",
                 "Rahul", "Mohit"],
        "Age": [22, 23, 25, 21, 27],
        "Qualification": ["BBA", "BCA", "BBA",
                          "BBA", "MBA"]
        }

# define dataframe
df = pd.DataFrame(data, columns=['Name', 'Age', 'Qualification'], index=[
                  'Person_A', 'Person_B', 'Person_AB', 'Person_C', 'Person_BC'])

# display original dataframe
print("\n Original Dataframe \n", df)

# filter index that contain an specific character.
df_1 = df.filter(like='B', axis=0)

# display result
print("\n display all indexes that contain Specific character \n", df_1)

Output


Next Article
Label-based indexing to the Pandas DataFrame

M

mukulsomukesh
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Python-pandas
  • Python pandas-dataFrame
  • Python Pandas-exercise
Practice Tags :
  • python

Similar Reads

    How to Filter DataFrame Rows Based on the Date in Pandas?
    Different regions follow different date conventions (YYYY-MM-DD, YYYY-DD-MM, DD/MM/YY, etc.).  It is difficult to work with such strings in the data. Pandas to_datetime() function allows converting the date and time in string format to datetime64. This datatype helps extract features of date and tim
    5 min read
    How to Filter DataFrame Rows Based on the Date in Pandas?
    Filtering a DataFrame rows by date selects all rows which satisfy specified date constraints, based on a column containing date data. For instance, selecting all rows between March 13, 2020, and December 31, 2020, would return all rows with date values in that range. Use DataFrame.loc() with the ind
    2 min read
    Filter Pandas DataFrame by Time
    In this article let's see how to filter pandas data frame by date. So we can filter python pandas data frame by date using the logical operator and loc() method. In the below examples we have a data frame that contains two columns the first column is Name and another one is DOB. Example 1: filter da
    1 min read
    Label-based indexing to the Pandas DataFrame
    Indexing plays an important role in data frames. Sometimes we need to give a label-based "fancy indexing" to the Pandas Data frame. For this, we have a function in pandas known as pandas.DataFrame.lookup(). The concept of Fancy Indexing is simple which means, we have to pass an array of indices to a
    3 min read
    Filtering rows based on column values in PySpark dataframe
    In this article, we are going to filter the rows based on column values in PySpark dataframe. Creating Dataframe for demonstration:Python3 # importing module import spark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app n
    2 min read
    Python | Pandas dataframe.filter()
    Pandas filter() function allows us to subset rows or columns in a DataFrame based on their labels. This method is useful when we need to select data based on label matching, whether it's by exact labels, partial string matches or regular expression patterns. It works with labels rather than the cont
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences