Bird
Raised Fist0
Pandasdata~20 mins

str.contains() for pattern matching in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pattern Matching Pro
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of str.contains() with case sensitivity
What is the output of the following code snippet?
Pandas
import pandas as pd

df = pd.DataFrame({'text': ['Apple', 'banana', 'Cherry', 'date']})
result = df['text'].str.contains('a')
print(result.tolist())
A[false, true, false, true]
B[true, true, true, true]
C[true, true, false, true]
D[true, false, false, true]
Attempts:
2 left
💡 Hint
Remember that str.contains() is case sensitive by default.
❓ data_output
intermediate
2:00remaining
Filter rows using str.contains() with regex
Given the DataFrame below, which rows remain after filtering with str.contains('^b.*a$', regex=true)?
Pandas
import pandas as pd

df = pd.DataFrame({'words': ['banana', 'beta', 'bat', 'boa', 'baba', 'cab']})
filtered = df[df['words'].str.contains('^b.*a$', regex=True)]
print(filtered['words'].tolist())
A['banana', 'beta', 'baba']
B['banana', 'beta', 'bat', 'baba']
C['banana', 'beta', 'baba', 'bat', 'boa']
D['banana', 'beta', 'boa', 'baba']
Attempts:
2 left
💡 Hint
The regex '^b.*a$' means strings starting with 'b' and ending with 'a'.
🔧 Debug
advanced
2:00remaining
Identify the error in str.contains() usage
What error does the following code raise?
Pandas
import pandas as pd

df = pd.DataFrame({'col': ['abc', 'def', 'ghi']})
result = df['col'].str.contains(123)
print(result)
ATypeError: expected string or bytes-like object
BValueError: invalid regex pattern
CAttributeError: 'int' object has no attribute 'contains'
DNo error, outputs a boolean Series
Attempts:
2 left
💡 Hint
Check the type of the pattern argument passed to str.contains().
🚀 Application
advanced
2:00remaining
Use str.contains() to find rows with multiple patterns
You want to filter rows where the 'text' column contains either 'cat' or 'dog'. Which code correctly does this?
Pandas
import pandas as pd

df = pd.DataFrame({'text': ['catfish', 'dogma', 'bird', 'catalog', 'frog']})
Adf[df['text'].str.contains('cat&dog')]
Bdf[df['text'].str.contains('cat|dog')]
Cdf[df['text'].str.contains(['cat', 'dog'])]
Ddf[df['text'].str.contains('cat,dog')]
Attempts:
2 left
💡 Hint
Use regex OR operator '|' inside the pattern string.
🧠 Conceptual
expert
2:00remaining
Understanding na parameter in str.contains()
What is the output of the following code?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame({'text': ['apple', np.nan, 'banana', np.nan]})
result = df['text'].str.contains('a', na=False)
print(result.tolist())
A[true, true, true, true]
B[true, true, false, false]
C[true, false, true, false]
D[true, false, true, true]
Attempts:
2 left
💡 Hint
The na parameter controls the output for missing values.

Practice

(1/5)
1. What does the str.contains() method do in pandas?
easy
A. It checks if a string pattern exists in each element of a Series.
B. It replaces strings matching a pattern with another string.
C. It counts the number of times a pattern appears in a Series.
D. It sorts the Series based on string length.

Solution

  1. Step 1: Understand the purpose of str.contains()

    This method is used to check if each string element in a pandas Series contains a specific pattern.
  2. Step 2: Compare with other string methods

    Replacing strings or counting occurrences are done by other methods like str.replace() or str.count(). Sorting is unrelated.
  3. Final Answer:

    It checks if a string pattern exists in each element of a Series. -> Option A
  4. Quick Check:

    str.contains() = check pattern presence [OK]
Hint: Remember: contains means 'is pattern inside?' [OK]
Common Mistakes:
  • Confusing contains with replace
  • Thinking it counts occurrences
  • Assuming it sorts data
2. Which of the following is the correct syntax to find rows where column 'Name' contains the substring 'John' (case insensitive) in a DataFrame df?
easy
A. df[df['Name'].str.contains('John', ignore_case=True)]
B. df[df['Name'].contains('John', case=False)]
C. df[df['Name'].str.contains('John', case=True)]
D. df[df['Name'].str.contains('John', case=False)]

Solution

  1. Step 1: Identify correct method and parameters

    The method is str.contains() and to ignore case, use case=False.
  2. 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)] misses str. df[df['Name'].str.contains('John', ignore_case=True)] uses wrong parameter ignore_case. df[df['Name'].str.contains('John', case=True)] sets case=True, which is case sensitive.
  3. Final Answer:

    df[df['Name'].str.contains('John', case=False)] -> Option D
  4. Quick Check:

    Use str.contains() with case=False [OK]
Hint: Use case=False for ignoring case in str.contains() [OK]
Common Mistakes:
  • Forgetting to use str accessor
  • Using wrong parameter name like ignore_case
  • Setting case=True when case insensitive needed
3. Given the DataFrame 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']})
medium
A. [False, True, False, False]
B. [True, False, False, False]
C. [True, True, False, False]
D. [True, True, True, False]

Solution

  1. Step 1: Check each element for 'York'

    'New York' contains 'York' (True), 'Yorkshire' contains 'York' (True), None is missing so replaced by False due to na=False, 'Los Angeles' does not contain 'York' (False).
  2. Step 2: Construct boolean Series output

    The result is [True, True, False, False].
  3. Final Answer:

    [True, True, False, False] -> Option C
  4. Quick Check:

    Check each string for 'York' with na=False [OK]
Hint: Use na=False to handle missing values safely [OK]
Common Mistakes:
  • Ignoring missing values causing errors
  • Assuming None matches pattern
  • Misreading which strings contain 'York'
4. What is wrong with this code snippet?
df[df['Email'].str.contains('@gmail.com')]
Assume some values in 'Email' column are missing (NaN).
medium
A. It will return all rows because '@gmail.com' matches everything.
B. It will raise an error due to missing values without handling na parameter.
C. It will ignore case sensitivity by default causing wrong results.
D. It will convert all emails to lowercase automatically.

Solution

  1. Step 1: Understand missing data impact on str.contains()

    If the column has NaN values, str.contains() raises an error unless na parameter is set.
  2. Step 2: Check code for na parameter

    The code does not set na=False, so it will raise an error when encountering NaN.
  3. Final Answer:

    It will raise an error due to missing values without handling na parameter. -> Option B
  4. Quick Check:

    Missing na causes errors with NaN [OK]
Hint: Always add na=False to avoid errors with missing data [OK]
Common Mistakes:
  • Ignoring NaN causes runtime error
  • Assuming default ignores case or missing data
  • Thinking it auto-lowers case
5. You have a DataFrame 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?
hard
A. df[df['Description'].str.contains('red|blue', case=False, na=False)]
B. df[df['Description'].str.contains('red|blue', case=True)]
C. df[df['Description'].str.contains('red|blue', na=True)]
D. df[df['Description'].str.contains('red|blue', case=False)]

Solution

  1. Step 1: Use regex pattern for multiple options

    To match 'red' or 'blue', use the regex pattern 'red|blue'.
  2. Step 2: Handle case insensitivity and missing values

    Set case=False for ignoring case and na=False to avoid errors on missing data.
  3. Step 3: Verify options

    df[df['Description'].str.contains('red|blue', case=False, na=False)] correctly uses both case=False and na=False. df[df['Description'].str.contains('red|blue', case=True)] is case sensitive. df[df['Description'].str.contains('red|blue', na=True)] uses invalid na=True. df[df['Description'].str.contains('red|blue', case=False)] misses na=False.
  4. Final Answer:

    df[df['Description'].str.contains('red|blue', case=False, na=False)] -> Option A
  5. Quick Check:

    Use regex with case=False and na=False [OK]
Hint: Use regex 'red|blue' with case=False and na=False [OK]
Common Mistakes:
  • Forgetting na=False causes errors
  • Using case sensitive search unintentionally
  • Wrong regex or missing regex for multiple patterns
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard