We use str.contains() to find if text data has a certain pattern or word. It helps us quickly check or filter data based on text.
str.contains() for pattern matching in Pandas
DataFrame['column_name'].str.contains(pattern, case=True, na=False, regex=True)
pattern is the text or regular expression you want to find.
case=True means matching is case sensitive. Use case=False to ignore case.
df['Name'].str.contains('John')
df['Email'].str.contains('@gmail.com', case=False)
df['Description'].str.contains('organic|natural', regex=True)
df['Phone'].str.contains('^\d{3}', regex=True)
This program creates a table of products with descriptions. It then finds all products whose description mentions 'organic' or 'natural', ignoring case. It prints the original and filtered tables.
import pandas as pd # Create a sample DataFrame products = pd.DataFrame({ 'Product': ['Apple Juice', 'Orange Juice', 'Organic Milk', 'Natural Honey', 'Regular Milk'], 'Description': ['Fresh apple juice', 'Sweet orange juice', '100% organic milk', 'Pure natural honey', None] }) print('Original DataFrame:') print(products) # Find rows where Description contains 'organic' or 'natural' ignoring case pattern = 'organic|natural' filtered = products[products['Description'].str.contains(pattern, case=False, na=False, regex=True)] print('\nFiltered DataFrame (contains "organic" or "natural"):') print(filtered)
Time complexity: O(n) where n is number of rows, because it checks each row's text.
Space complexity: O(n) for the boolean mask created during filtering.
Common mistake: Forgetting na=False causes errors if there are missing values.
Use str.contains() when you want to check if text includes a pattern. Use other methods like str.startswith() if you only want to check the start.
str.contains() helps find text patterns in columns.
It supports case sensitivity and regular expressions.
Always handle missing data with na=False to avoid errors.
Practice
str.contains() method do in pandas?Solution
Step 1: Understand the purpose of
This method is used to check if each string element in a pandas Series contains a specific pattern.str.contains()Step 2: Compare with other string methods
Replacing strings or counting occurrences are done by other methods likestr.replace()orstr.count(). Sorting is unrelated.Final Answer:
It checks if a string pattern exists in each element of a Series. -> Option AQuick Check:
str.contains()= check pattern presence [OK]
- Confusing contains with replace
- Thinking it counts occurrences
- Assuming it sorts data
df?Solution
Step 1: Identify correct method and parameters
The method isstr.contains()and to ignore case, usecase=False.Step 2: Check syntax correctness
df[df['Name'].str.contains('John', case=False)] uses correct method and parameter. df[df['Name'].contains('John', case=False)] missesstr. df[df['Name'].str.contains('John', ignore_case=True)] uses wrong parameterignore_case. df[df['Name'].str.contains('John', case=True)] setscase=True, which is case sensitive.Final Answer:
df[df['Name'].str.contains('John', case=False)] -> Option DQuick Check:
Usestr.contains()withcase=False[OK]
case=False for ignoring case in str.contains() [OK]- Forgetting to use
straccessor - Using wrong parameter name like
ignore_case - Setting
case=Truewhen case insensitive needed
df below, what is the output of df['City'].str.contains('York', na=False)?
import pandas as pd
df = pd.DataFrame({'City': ['New York', 'Yorkshire', None, 'Los Angeles']})Solution
Step 1: Check each element for 'York'
'New York' contains 'York' (True), 'Yorkshire' contains 'York' (True), None is missing so replaced by False due tona=False, 'Los Angeles' does not contain 'York' (False).Step 2: Construct boolean Series output
The result is [True, True, False, False].Final Answer:
[True, True, False, False] -> Option CQuick Check:
Check each string for 'York' withna=False[OK]
na=False to handle missing values safely [OK]- Ignoring missing values causing errors
- Assuming None matches pattern
- Misreading which strings contain 'York'
df[df['Email'].str.contains('@gmail.com')]
Assume some values in 'Email' column are missing (NaN).Solution
Step 1: Understand missing data impact on
If the column has NaN values,str.contains()str.contains()raises an error unlessnaparameter is set.Step 2: Check code for
The code does not setnaparameterna=False, so it will raise an error when encountering NaN.Final Answer:
It will raise an error due to missing values without handlingnaparameter. -> Option BQuick Check:
Missingnacauses errors with NaN [OK]
na=False to avoid errors with missing data [OK]- Ignoring NaN causes runtime error
- Assuming default ignores case or missing data
- Thinking it auto-lowers case
df with a column 'Description' containing product details. You want to filter rows where 'Description' contains either 'red' or 'blue' (case insensitive), but some rows have missing values. Which code snippet correctly does this?Solution
Step 1: Use regex pattern for multiple options
To match 'red' or 'blue', use the regex pattern 'red|blue'.Step 2: Handle case insensitivity and missing values
Setcase=Falsefor ignoring case andna=Falseto avoid errors on missing data.Step 3: Verify options
df[df['Description'].str.contains('red|blue', case=False, na=False)] correctly uses bothcase=Falseandna=False. df[df['Description'].str.contains('red|blue', case=True)] is case sensitive. df[df['Description'].str.contains('red|blue', na=True)] uses invalidna=True. df[df['Description'].str.contains('red|blue', case=False)] missesna=False.Final Answer:
df[df['Description'].str.contains('red|blue', case=False, na=False)] -> Option AQuick Check:
Use regex withcase=Falseandna=False[OK]
case=False and na=False [OK]- Forgetting
na=Falsecauses errors - Using case sensitive search unintentionally
- Wrong regex or missing regex for multiple patterns
Ready to prove it?
Pass the test and this pattern moves unknown
