Bird
Raised Fist0
Pandasdata~20 mins

str accessor for string methods in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Str Accessor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of str.upper() on a pandas Series
What is the output of the following code?
import pandas as pd
s = pd.Series(['apple', 'Banana', 'Cherry'])
result = s.str.upper()
print(result)
Pandas
import pandas as pd
s = pd.Series(['apple', 'Banana', 'Cherry'])
result = s.str.upper()
print(result)
A
0    APPLE
1    Banana
2    CHERRY
dtype: object
B
0     APPLE
1    BANANA
2    CHERRY
dtype: object
C
0    apple
1    Banana
2    Cherry
dtype: object
D
0    apple
1    BANANA
2    cherry
dtype: object
Attempts:
2 left
💡 Hint
The str.upper() method converts all characters in each string to uppercase.
❓ data_output
intermediate
2:00remaining
Count of strings containing 'a' using str.contains()
Given the Series below, what is the count of strings that contain the letter 'a' (case insensitive)?
import pandas as pd
s = pd.Series(['Cat', 'dog', 'Parrot', 'fish', 'ant'])
count = s.str.contains('a', case=False).sum()
print(count)
Pandas
import pandas as pd
s = pd.Series(['Cat', 'dog', 'Parrot', 'fish', 'ant'])
count = s.str.contains('a', case=False).sum()
print(count)
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
Check which strings have 'a' or 'A' in them.
🔧 Debug
advanced
2:00remaining
Identify the error in using str.replace()
What error does the following code raise?
import pandas as pd
s = pd.Series(['apple', 'banana', 'cherry'])
result = s.str.replace('a', 1)
print(result)
Pandas
import pandas as pd
s = pd.Series(['apple', 'banana', 'cherry'])
result = s.str.replace('a', 1)
print(result)
AAttributeError: 'Series' object has no attribute 'str'
BValueError: invalid replacement string
CTypeError: expected string or bytes-like object
DNo error, output is ['1pple', 'b1n1n1', 'cherry']
Attempts:
2 left
💡 Hint
Check the type of the replacement argument in str.replace.
❓ visualization
advanced
2:00remaining
Visualize string length distribution using str.len()
You have a pandas Series of words. Which code snippet correctly creates a histogram of their lengths?
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(['dog', 'elephant', 'cat', 'hippopotamus', 'fox'])
# Which code below creates the histogram?
Pandas
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(['dog', 'elephant', 'cat', 'hippopotamus', 'fox'])
A
plt.hist(s.str.len())
plt.show()
B
plt.hist(s.len())
plt.show()
C
plt.hist(len(s))
plt.show()
D
plt.hist(s.str.length())
plt.show()
Attempts:
2 left
💡 Hint
Use the str accessor to get string lengths.
🚀 Application
expert
3:00remaining
Filter DataFrame rows where a column's strings start with a vowel
Given the DataFrame below, which code correctly filters rows where the 'Name' column starts with a vowel (a, e, i, o, u), case insensitive?
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'bob', 'Eve', 'Oscar', 'Uma', 'Charlie']})
Pandas
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'bob', 'Eve', 'Oscar', 'Uma', 'Charlie']})
A
filtered = df[df['Name'].str.match('[aeiou]$', case=False)]
print(filtered)
B
filtered = df[df['Name'].str.startswith('aeiou')]
print(filtered)
C
filtered = df[df['Name'].str.contains('^[aeiou]', case=True)]
print(filtered)
D
filtered = df[df['Name'].str.match('^[aeiou]', case=False)]
print(filtered)
Attempts:
2 left
💡 Hint
Use a regex pattern with str.match to check the start of the string.

Practice

(1/5)
1. What does the str accessor in pandas allow you to do with a DataFrame column?
easy
A. Perform mathematical operations on numeric data
B. Sort the DataFrame rows by index
C. Apply string methods to each element in the column
D. Merge two DataFrames based on a key column

Solution

  1. Step 1: Understand the purpose of the str accessor

    The str accessor is designed to apply string methods element-wise on pandas Series or DataFrame columns containing text data.
  2. Step 2: Compare options with the str accessor's function

    Performing mathematical operations on numeric data, sorting the DataFrame rows by index, and merging two DataFrames based on a key column are unrelated to string methods. Only applying string methods to each element in the column correctly describes the str accessor's function.
  3. Final Answer:

    Apply string methods to each element in the column -> Option C
  4. Quick Check:

    str accessor = apply string methods [OK]
Hint: Remember: str accessor works only on text columns [OK]
Common Mistakes:
  • Thinking str accessor works on numbers
  • Confusing str accessor with DataFrame merge
  • Assuming str accessor sorts data
2. Which of the following is the correct syntax to convert all strings in a pandas Series names to lowercase using the str accessor?
easy
A. names.str.lower()
B. names.lower()
C. str.lower(names)
D. names.to_lower()

Solution

  1. Step 1: Recall the correct usage of str accessor

    To apply string methods on a pandas Series, use Series.str.method(). Here, lower() converts strings to lowercase.
  2. Step 2: Evaluate each option

    names.str.lower() uses names.str.lower(), which is correct. names.lower() misses str. str.lower(names) incorrectly calls str.lower as a function with Series argument. names.to_lower() uses a non-existent method to_lower().
  3. Final Answer:

    names.str.lower() -> Option A
  4. Quick Check:

    Use Series.str.method() for string methods [OK]
Hint: Always use .str before string methods on Series [OK]
Common Mistakes:
  • Calling string methods directly on Series without .str
  • Using wrong method names like to_lower()
  • Passing Series as argument to str functions
3. Given the pandas Series data = pd.Series(['Apple', 'Banana', 'Cherry']), what is the output of data.str[0]?
medium
A. ['Apple', 'Banana', 'Cherry']
B. ['A', 'B', 'C']
C. ['pple', 'anana', 'herry']
D. Error: cannot index strings this way

Solution

  1. Step 1: Understand what data.str[0] does

    The str accessor allows indexing each string element. str[0] extracts the first character of each string in the Series.
  2. Step 2: Apply indexing to each element

    For 'Apple', first character is 'A'; for 'Banana', 'B'; for 'Cherry', 'C'. So the result is ['A', 'B', 'C'].
  3. Final Answer:

    ['A', 'B', 'C'] -> Option B
  4. Quick Check:

    str[0] = first char of each string [OK]
Hint: str[index] extracts character at position index [OK]
Common Mistakes:
  • Expecting full strings instead of first chars
  • Thinking it slices off first char
  • Assuming error occurs on indexing
4. What is wrong with this code snippet?
df = pd.DataFrame({'col': ['a', 'b', 'c']})
df['col'] = df['col'].str.upper
medium
A. Missing parentheses to call the method
B. Using .str.upper on numeric data
C. DataFrame column name is invalid
D. str accessor cannot be used on DataFrame columns

Solution

  1. Step 1: Identify the method call syntax error

    The code assigns df['col'].str.upper without parentheses, so it assigns the method itself, not the result of calling it.
  2. Step 2: Correct the code

    Adding parentheses df['col'].str.upper() calls the method and returns the uppercase strings.
  3. Final Answer:

    Missing parentheses to call the method -> Option A
  4. Quick Check:

    Call string methods with () [OK]
Hint: Always add () to call string methods [OK]
Common Mistakes:
  • Forgetting parentheses after string methods
  • Trying to use str methods on numbers
  • Confusing Series and DataFrame usage
5. You have a DataFrame df with a column 'email' containing email addresses. How would you extract the domain part (after '@') for each email using the str accessor?
hard
A. df['email'].str.find('@')
B. df['email'].str.replace('@', '')
C. df['email'].str.upper()
D. df['email'].str.split('@').str[1]

Solution

  1. Step 1: Understand the goal to extract domain after '@'

    We want the part of the string after '@' in each email address.
  2. Step 2: Use str.split('@') to split each string into two parts

    Splitting by '@' creates a list like ['user', 'domain.com']. Using str[1] selects the domain part.
  3. Step 3: Check other options

    df['email'].str.replace('@', '') removes '@' but does not extract domain. df['email'].str.find('@') returns index of '@', not domain. df['email'].str.upper() converts to uppercase, unrelated.
  4. Final Answer:

    df['email'].str.split('@').str[1] -> Option D
  5. Quick Check:

    Split by '@' then select index 1 [OK]
Hint: Split by '@' then pick second part with str[1] [OK]
Common Mistakes:
  • Using replace instead of split
  • Trying to find index instead of extracting substring
  • Ignoring method chaining with str accessor
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