Regex operations in Pandas - Time & Space Complexity
When we use regex operations in pandas, we want to know how the time it takes changes as our data grows.
We ask: How does searching or matching patterns slow down when we have more data?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'text': ['apple123', 'banana456', 'cherry789', 'date012'] * 1000
})
matches = df['text'].str.contains(r'\d{3}')
This code checks each string in the 'text' column to see if it contains three digits in a row.
- Primary operation: Applying the regex pattern to each string in the column.
- How many times: Once for every row in the DataFrame.
As the number of rows grows, the total work grows roughly in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 regex checks |
| 100 | About 100 regex checks |
| 1000 | About 1000 regex checks |
Pattern observation: Doubling the rows roughly doubles the work because each row is checked once.
Time Complexity: O(n)
This means the time grows linearly with the number of rows; more rows mean proportionally more work.
[X] Wrong: "Regex operations take constant time no matter how many rows there are."
[OK] Correct: Each row is checked separately, so more rows mean more checks and more time.
Understanding how regex operations scale helps you explain your code's speed and handle bigger data confidently.
"What if we changed the regex to a more complex pattern that takes longer to match? How would the time complexity change?"
Practice
str.contains method do in Pandas when used with a regex pattern?Solution
Step 1: Understand
str.containsusagestr.containschecks if the regex pattern appears anywhere in each string of the column and returns a boolean Series.Step 2: Differentiate from other methods
str.replacechanges text,str.extractpulls out matches, and sorting is unrelated.Final Answer:
It checks if each string in a column contains the regex pattern and returns true or false. -> Option DQuick Check:
str.contains= Boolean check [OK]
- Confusing contains with replace or extract
- Thinking contains modifies the data
- Assuming contains returns matched text
df['col'] with the character 'X' using regex?Solution
Step 1: Identify correct method for regex replacement
Usestr.replaceon the Series to replace regex matches. df['col'].replace('[0-9]', 'X') is wrong becausereplacewithoutstris for exact values, not regex.Step 2: Check regex pattern and syntax
df['col'].str.replace('[0-9]', 'X') matches single digits only ('123' -> 'XXX'). df['col'].str.replace('\d+', 'X') matches sequences of one or more digits ('123' -> 'X').Final Answer:
df['col'].str.replace('\d+', 'X') -> Option AQuick Check:
Usestr.replacewith regex pattern [OK]
- Using DataFrame replace instead of Series.str.replace
- Wrong regex pattern syntax
- Using str.extract instead of replace
import pandas as pd
df = pd.DataFrame({'text': ['apple123', 'banana', 'cherry456', 'date789']})
df['numbers'] = df['text'].str.extract('(\d+)')What will be the content of the new column
numbers?Solution
Step 1: Understand
The regexstr.extractwith regex(\d+)captures one or more digits.str.extractreturns the first match or NaN if none.Step 2: Apply regex to each string
'apple123' matches '123', 'banana' has no digits so NaN, 'cherry456' matches '456', 'date789' matches '789'.Final Answer:
['123', NaN, '456', '789'] -> Option CQuick Check:
Extract digits or NaN if none [OK]
- Expecting extract to return full string
- Confusing extract with contains or replace
- Not handling NaN for no matches
import pandas as pd
df = pd.DataFrame({'col': ['abc123', 'def456', 'ghi789']})
df['col'].str.match('[a-z]+\d')What is the error or issue in this code?
Solution
Step 1: Analyze the regex pattern
The pattern[a-z]+\dmatches one or more lowercase letters followed by exactly one digit from the start of the string.Step 2: Compare pattern with data strings
The strings 'abc123', 'def456', 'ghi789' have multiple digits at the end, but the pattern only expects one digit. Sincestr.matchmatches from the start and the pattern does not cover the full digit sequence, it returns False for all rows.Final Answer:
The regex pattern misses the last digit, so match returns false for all rows. -> Option AQuick Check:
str.matchmatches from start; pattern must cover full prefix for True [OK]
- Thinking str.match requires full string match
- Confusing str.match with str.fullmatch
- Thinking regex syntax is invalid here
df with a column 'emails' containing email addresses mixed with invalid entries. How would you create a new column 'valid' that is true only for rows where 'emails' contains a valid email pattern using regex in Pandas?Solution
Step 1: Choose method to check pattern presence
str.containsreturns true/false if regex matches anywhere in string, suitable for validation.Step 2: Use correct regex for full email validation
The regex^[\w\.-]+@[\w\.-]+\.\w+$matches a full email pattern from start to end. df['valid'] = df['emails'].str.extract(r'^[\w\.-]+@[\w\.-]+\.\w+$') extracts matched text, not boolean. df['valid'] = df['emails'].str.replace(r'^[\w\.-]+@[\w\.-]+\.\w+$', 'true') replaces text, not boolean. df['valid'] = df['emails'].str.match(r'\w+@\w+') usesstr.matchbut regex is incomplete and may match partial emails.Final Answer:
df['valid'] = df['emails'].str.contains(r'^[\w\.-]+@[\w\.-]+\.\w+$') -> Option BQuick Check:
Use str.contains with full regex for validation [OK]
- Using str.extract which returns strings, not booleans
- Using str.replace which changes data instead of checking
- Using incomplete regex that matches partial emails
Ready to prove it?
Pass the test and this pattern moves unknown
