Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Pattern matching with str.contains in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pattern Matching Master
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 this code snippet?
Data Analysis Python
import pandas as pd

data = pd.Series(['Apple', 'banana', 'Cherry', 'date'])
result = data.str.contains('a')
print(result.tolist())
A[True, False, False, True]
B[True, True, False, True]
C[True, True, True, True]
D[False, True, False, True]
Attempts:
2 left
💡 Hint
Remember that str.contains is case sensitive by default.
❓ data_output
intermediate
2:00remaining
Filtering DataFrame rows with str.contains and regex
Given the DataFrame below, which rows are selected by the filter df[df['Name'].str.contains('^J.*n$', regex=True)]?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'Name': ['John', 'Jason', 'Jordan', 'Joan', 'Jan', 'Jim']})
filtered = df[df['Name'].str.contains('^J.*n$', regex=True)]
print(filtered['Name'].tolist())
A['John', 'Jordan', 'Jan']
B['John', 'Jason', 'Jordan', 'Joan', 'Jan']
C['John', 'Jordan', 'Joan', 'Jan']
D['John', 'Jan']
Attempts:
2 left
💡 Hint
The regex '^J.*n$' means strings starting with 'J' and ending with 'n'.
🔧 Debug
advanced
2:00remaining
Identify the error in str.contains usage
What error does this code raise?
Data Analysis Python
import pandas as pd

data = pd.Series(['cat', 'dog', 'bird'])
result = data.str.contains('[a-z')
print(result)
AValueError: Unbalanced bracket expression
BSyntaxError
CTypeError
DNo error, outputs a boolean Series
Attempts:
2 left
💡 Hint
Check the regex pattern for correctness.
❓ visualization
advanced
2:00remaining
Visualizing pattern match counts in a DataFrame
Which code snippet correctly creates a bar chart showing counts of rows where 'City' contains 'York' (case insensitive)?
Data Analysis Python
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'City': ['New York', 'Yorkshire', 'Los Angeles', 'york', 'Boston']})

# Which code below produces the correct bar chart?
A
counts = df['City'].str.contains('York', case=True).value_counts()
counts.plot(kind='bar')
plt.show()
B
counts = df['City'].str.contains('York').value_counts()
counts.plot(kind='bar')
plt.show()
C
counts = df['City'].str.contains('York', case=False).value_counts()
counts.plot(kind='bar')
plt.show()
D
counts = df['City'].str.contains('york', case=True).value_counts()
counts.plot(kind='bar')
plt.show()
Attempts:
2 left
💡 Hint
Look for case insensitive matching.
🚀 Application
expert
3:00remaining
Extracting and counting patterns with str.contains and groupby
You have a DataFrame with a 'Text' column containing sentences. You want to count how many rows mention either 'cat' or 'dog' (case insensitive). Which code snippet correctly produces a DataFrame with counts for each animal?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'Text': ['I love my Cat', 'Dog is friendly', 'Cats and dogs', 'No pets here', 'dog and cat']})

# Which code below produces a DataFrame with counts of rows mentioning 'cat' and 'dog'?
A
counts = df['Text'].str.contains('cat|dog', case=False).value_counts()
print(counts)
B
counts = pd.Series({
    'cat': df['Text'].str.contains('cat', case=False).sum(),
    'dog': df['Text'].str.contains('dog', case=False).sum()
}).to_frame('Count')
print(counts)
C
counts = df['Text'].apply(lambda x: 'cat' if 'cat' in x else ('dog' if 'dog' in x else None)).value_counts()
print(counts)
D
counts = df['Text'].str.extractall('(cat|dog)', flags=re.IGNORECASE).groupby(0).size().to_frame('Count')
print(counts)
Attempts:
2 left
💡 Hint
Use str.contains for each animal separately and sum the booleans.

Practice

(1/5)
1. What does the str.contains method do when used on a pandas Series?
easy
A. It replaces all occurrences of a pattern with another string.
B. It counts how many times a pattern appears in each string.
C. It splits each string into a list based on a pattern.
D. It checks if each string contains a specified pattern and returns true or false.

Solution

  1. Step 1: Understand str.contains purpose

    The method checks each string in a Series for a pattern and returns true or false accordingly.
  2. Step 2: Compare with other string methods

    Replacing, splitting, or counting are different methods like replace(), split(), or count(), not contains().
  3. Final Answer:

    It checks if each string contains a specified pattern and returns true or false. -> Option D
  4. Quick Check:

    str.contains returns boolean mask [OK]
Hint: Remember: contains returns true/false for pattern presence [OK]
Common Mistakes:
  • Confusing contains with replace or split
  • Thinking it returns counts instead of booleans
  • Assuming it modifies the original data
2. Which of the following is the correct syntax to filter rows in a DataFrame df where the column 'name' contains the substring 'cat'?
easy
A. df[df['name'].str.contain('cat')]
B. df[df['name'].contains('cat')]
C. df[df['name'].str.contains('cat')]
D. df[df['name'].str.contains(cat)]

Solution

  1. Step 1: Identify correct method usage

    The correct method is str.contains called on the Series with the pattern as a string argument.
  2. Step 2: Check syntax details

    df[df['name'].str.contains('cat')] uses str.contains('cat') correctly with quotes around 'cat'. df[df['name'].contains('cat')] misses str, C has a typo, D misses quotes around 'cat'.
  3. Final Answer:

    df[df['name'].str.contains('cat')] -> Option C
  4. Quick Check:

    Use str.contains with string pattern in quotes [OK]
Hint: Use df['col'].str.contains('pattern') with quotes [OK]
Common Mistakes:
  • Forgetting to use .str before contains
  • Missing quotes around the pattern string
  • Typo in method name like contain instead of contains
3. Given the DataFrame 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?
medium
A. Rows where 'text' contains 'apple': 'apple pie' and 'apple turnover'.
B. Rows where 'text' contains 'banana' only.
C. All rows because 'apple' is in every string.
D. An empty DataFrame because 'apple' is not found.

Solution

  1. Step 1: Check which rows contain 'apple'

    Rows 0 ('apple pie') and 3 ('apple turnover') contain the substring 'apple'.
  2. Step 2: Understand filtering result

    The filter returns only these rows, excluding others like 'banana split' and 'cherry tart'.
  3. Final Answer:

    Rows where 'text' contains 'apple': 'apple pie' and 'apple turnover'. -> Option A
  4. Quick Check:

    Filter keeps rows with 'apple' substring [OK]
Hint: Filter keeps only rows where pattern is found [OK]
Common Mistakes:
  • Assuming all rows are returned
  • Confusing 'apple' with other fruits
  • Expecting a count instead of filtered rows
4. Consider this code snippet:
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?
medium
A. TypeError because df is not defined; import pandas first.
B. NameError because 'cat' is not quoted; fix by using 'cat' in quotes.
C. AttributeError because str.contains is misspelled; fix spelling.
D. No error; code runs correctly.

Solution

  1. Step 1: Identify cause of error

    The pattern 'cat' is used without quotes, so Python treats it as a variable, causing NameError.
  2. Step 2: Correct the syntax

    Put 'cat' in quotes: str.contains('cat') to pass a string pattern.
  3. Final Answer:

    NameError because 'cat' is not quoted; fix by using 'cat' in quotes. -> Option B
  4. Quick Check:

    Pattern must be a string in quotes [OK]
Hint: Always quote string patterns in str.contains [OK]
Common Mistakes:
  • Forgetting quotes around pattern
  • Assuming pattern can be variable without definition
  • Ignoring error messages about undefined names
5. You have a DataFrame 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?
hard
A. df[df['comments'].str.contains('error|fail', case=false)]
B. df[df['comments'].str.contains('error' or 'fail', case=true)]
C. df[df['comments'].str.contains(['error', 'fail'], case=false)]
D. df[df['comments'].str.contains('error|fail', case=true)]

Solution

  1. Step 1: Use regex pattern for multiple words

    To match 'error' or 'fail', use regex 'error|fail' inside str.contains.
  2. Step 2: Set case insensitive matching

    Use case=false to ignore case differences.
  3. 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.
  4. Final Answer:

    df[df['comments'].str.contains('error|fail', case=false)] -> Option A
  5. Quick Check:

    Use regex with | and case=false for case-insensitive OR [OK]
Hint: Use regex 'word1|word2' with case=false for OR matching [OK]
Common Mistakes:
  • Using Python 'or' inside string instead of regex |
  • Passing list instead of string pattern
  • Forgetting case=false for case-insensitive search
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