We use pattern matching with str.contains to find rows in data that have certain words or patterns. It helps us quickly filter data based on text.
Pattern matching with str.contains in Data Analysis Python
import pandas as pd data = pd.Series(['apple', 'banana', 'cherry', 'date']) mask = data.str.contains('an') filtered_data = data[mask]
The str.contains method returns a boolean series showing True where the pattern is found.
You can use regular expressions for complex patterns or simple strings for exact matches.
import pandas as pd data = pd.Series(['apple', 'banana', 'cherry', 'date']) # Find items containing 'an' mask = data.str.contains('an') print(data[mask])
import pandas as pd data = pd.Series(['apple', 'banana', 'cherry', 'date']) # What if the series is empty? empty_data = pd.Series([], dtype=object) mask_empty = empty_data.str.contains('a') print(empty_data[mask_empty])
import pandas as pd data = pd.Series(['apple']) # Only one element, check if it contains 'a' mask_single = data.str.contains('a') print(data[mask_single])
import pandas as pd data = pd.Series(['apple', 'banana', 'cherry', 'date']) # Check if elements start with 'a' using regex mask_start_a = data.str.contains('^a') print(data[mask_start_a])
This program shows the original list of fruits and then filters to show only those containing the letter 'a'.
import pandas as pd # Create a Series of fruit names fruit_names = pd.Series(['apple', 'banana', 'cherry', 'date', 'avocado']) print('Original data:') print(fruit_names) # Find fruits containing the letter 'a' contains_a_mask = fruit_names.str.contains('a') filtered_fruits = fruit_names[contains_a_mask] print('\nFruits containing the letter "a":') print(filtered_fruits)
Time complexity: O(n) where n is the number of elements, because it checks each string once.
Space complexity: O(n) for the boolean mask created.
Common mistake: Forgetting that str.contains returns a boolean series, so you must use it to filter the original data.
Use str.contains when you want to filter data by text patterns. For exact matches, consider using == or str.match for full string matches.
Pattern matching with str.contains helps find text inside data easily.
It returns True or False for each item, so you can filter your data.
You can use simple words or complex patterns with regular expressions.
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
