What if you could find any phrase in thousands of texts in just one line of code?
Why Pattern matching with str.contains in Data Analysis Python? - Purpose & Use Cases
Imagine you have a long list of customer reviews and you want to find all reviews that mention the word "great" or "excellent". Doing this by reading each review one by one is like searching for a needle in a haystack.
Manually scanning through hundreds or thousands of text entries is slow and tiring. You might miss some because of typos or different word forms. It's easy to make mistakes and hard to keep track of what you found.
Using str.contains lets you quickly check if each text entry has the pattern you want. It works fast on big lists and can handle variations like uppercase or lowercase letters automatically.
matches = [] for review in reviews: if 'great' in review.lower() or 'excellent' in review.lower(): matches.append(review)
matches = reviews[reviews.str.contains('great|excellent', case=False, na=False)]
You can instantly filter and analyze large text data to find meaningful patterns without reading every word.
A company can quickly find all customer feedback mentioning "slow service" or "friendly staff" to improve their business.
Manually searching text is slow and error-prone.
str.contains makes pattern matching fast and easy.
This helps analyze large text data efficiently.
Practice
str.contains method do when used on a pandas Series?Solution
Step 1: Understand str.contains purpose
The method checks each string in a Series for a pattern and returns true or false accordingly.Step 2: Compare with other string methods
Replacing, splitting, or counting are different methods like replace(), split(), or count(), not contains().Final Answer:
It checks if each string contains a specified pattern and returns true or false. -> Option DQuick Check:
str.contains returns boolean mask [OK]
- Confusing contains with replace or split
- Thinking it returns counts instead of booleans
- Assuming it modifies the original data
df where the column 'name' contains the substring 'cat'?Solution
Step 1: Identify correct method usage
The correct method isstr.containscalled on the Series with the pattern as a string argument.Step 2: Check syntax details
df[df['name'].str.contains('cat')] usesstr.contains('cat')correctly with quotes around 'cat'. df[df['name'].contains('cat')] missesstr, C has a typo, D misses quotes around 'cat'.Final Answer:
df[df['name'].str.contains('cat')] -> Option CQuick Check:
Use str.contains with string pattern in quotes [OK]
- Forgetting to use .str before contains
- Missing quotes around the pattern string
- Typo in method name like contain instead of contains
df below:import pandas as pd
df = pd.DataFrame({'text': ['apple pie', 'banana split', 'cherry tart', 'apple turnover']})
What will
df[df['text'].str.contains('apple')] return?Solution
Step 1: Check which rows contain 'apple'
Rows 0 ('apple pie') and 3 ('apple turnover') contain the substring 'apple'.Step 2: Understand filtering result
The filter returns only these rows, excluding others like 'banana split' and 'cherry tart'.Final Answer:
Rows where 'text' contains 'apple': 'apple pie' and 'apple turnover'. -> Option AQuick Check:
Filter keeps rows with 'apple' substring [OK]
- Assuming all rows are returned
- Confusing 'apple' with other fruits
- Expecting a count instead of filtered rows
import pandas as pd
df = pd.DataFrame({'col': ['dog', 'cat', 'bird']})
filtered = df[df['col'].str.contains(cat)]
print(filtered)What is the error and how to fix it?
Solution
Step 1: Identify cause of error
The pattern 'cat' is used without quotes, so Python treats it as a variable, causing NameError.Step 2: Correct the syntax
Put 'cat' in quotes:str.contains('cat')to pass a string pattern.Final Answer:
NameError because 'cat' is not quoted; fix by using 'cat' in quotes. -> Option BQuick Check:
Pattern must be a string in quotes [OK]
- Forgetting quotes around pattern
- Assuming pattern can be variable without definition
- Ignoring error messages about undefined names
df with a column 'comments' containing text. You want to filter rows where 'comments' contain either 'error' or 'fail' (case insensitive). Which code correctly does this?Solution
Step 1: Use regex pattern for multiple words
To match 'error' or 'fail', use regex 'error|fail' inside str.contains.Step 2: Set case insensitive matching
Usecase=falseto ignore case differences.Step 3: Check options
df[df['comments'].str.contains('error|fail', case=false)] correctly uses regex and case=false. df[df['comments'].str.contains('error' or 'fail', case=true)] misuses 'or' inside string, C passes list instead of string, A uses case=true which is case sensitive.Final Answer:
df[df['comments'].str.contains('error|fail', case=false)] -> Option AQuick Check:
Use regex with | and case=false for case-insensitive OR [OK]
- Using Python 'or' inside string instead of regex |
- Passing list instead of string pattern
- Forgetting case=false for case-insensitive search
Ready to prove it?
Pass the test and this pattern moves unknown
