Open In App

Get All Rows in a Pandas DataFrame Containing given Substring

Last Updated : 03 Oct, 2025
Comments
Improve
Suggest changes
14 Likes
Like
Report

If you want to filter rows in a Pandas DataFrame based on whether a column contains a specific substring, you can use the str.contains() function. For example, you might want only rows where "Team" contains "Boston" or "Position" contains "PG".

For Example: This example shows how to select rows where a column contains "yes".

Python
import pandas as pd  
df = pd.DataFrame({"Answer": ["yes", "no", "maybe", "yes"]})  
print(df[df["Answer"].str.contains("yes")])  

Output
  Answer
0    yes
3    yes

Explanation: Here we checked the "Answer" column and returned only rows containing "yes".

Syntax

DataFrame[DataFrame['column'].str.contains("substring")]

Parameters:

  • column: Column name where the search is applied.
  • substring: The text you want to match.

Return Value: A DataFrame with rows containing the given substring.

Examples

We will use the following DataFrame in all examples:

Python
import pandas as pd  

df = pd.DataFrame({ "Name": ["Alex", "Bob", "Cathy", "David", "Eva"],  
                    "Team": ["Boston Celtics", "LA Lakers", "Boston Celtics", "Chicago Bulls", "Boston Celtics"],  
                    "Position": ["PG", "SG", "PG", "UG", "PG"],  
                    "College": ["MIT", "Stanford", "Harvard", "UC Berkeley", "UC Davis"] })  
print(df)

Output

Name Team Position College
0 Alex Boston Celtics PG MIT
1 Emily LA Lakers SG Stanford
2 Cathy Boston Celtics PG Harvard
3 David Chicago Bulls UG UC Berkeley
4 Eva Boston Celtics PG UC Davis

Example 1: This example filters rows where the "Position" column contains "PG".

Python
result = df[df["Position"].str.contains("PG")]  
print(result)

Output

Name Team Position College
0 Alex Boston Celtics PG MIT
2 Cathy Boston Celtics PG Harvard
4 Eva Boston Celtics PG UC Davis

Example 2: This code selects rows where the "College" column contains "UC".

Python
result = df[df["College"].str.contains("UC")]  
print(result)

Output

Name Team Position College
3 David Chicago Bulls UG UC Berkeley
4 Eva Boston Celtics PG UC Davis

Example 3: This program filters rows that satisfy at least one of the conditions: "Team" contains "Boston" OR "College" contains "MIT".

Python
result = df[df["Team"].str.contains("Boston") | df["College"].str.contains("MIT")]  
print(result)

Output

Name Team Position College
0 Alex Boston Celtics PG MIT
2 Cathy Boston Celtics PG Harvard
4 Eva Boston Celtics PG UC Davis

Explanation: The | operator means “OR”, so rows are included if either condition is true.


Explore