str.contains() for pattern matching in Pandas - Time & Space Complexity
We want to understand how the time needed to find patterns in text grows as the data gets bigger.
How does using str.contains() on many text entries affect the time it takes?
Analyze the time complexity of the following code snippet.
import pandas as pd
data = pd.Series(["apple", "banana", "apricot", "cherry", "pineapple"] * 1000)
pattern = "app"
matches = data.str.contains(pattern)
This code checks each string in the series to see if it contains the pattern "app".
- Primary operation: Checking each string for the pattern using
str.contains(). - How many times: Once for each string in the series (n times).
Each string is checked one by one. If there are more strings, the work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 pattern checks |
| 100 | 100 pattern checks |
| 1000 | 1000 pattern checks |
Pattern observation: Doubling the number of strings roughly doubles the work.
Time Complexity: O(n * m)
This means the time grows with the number of strings (n) and the average length of each string (m).
[X] Wrong: "The time only depends on the number of strings, not their length."
[OK] Correct: Each string's length affects how long the pattern search takes, so longer strings mean more work per check.
Understanding how pattern matching scales helps you explain and improve text search tasks in real projects.
"What if we used a compiled regular expression with str.contains()? How would the time complexity change?"
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
