Skip to content
-
Filter Pandas DataFrame Based on Index
Last Updated :
23 Mar, 2022
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

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");
}