Challenge - 5 Problems
Replace Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of replace() on a pandas DataFrame column
What is the output of the following code snippet?
Data Analysis Python
import pandas as pd df = pd.DataFrame({'Fruit': ['apple', 'banana', 'cherry', 'banana', 'apple']}) df['Fruit'] = df['Fruit'].replace('banana', 'orange') print(df)
Attempts:
2 left
💡 Hint
replace() changes all exact matches of the old value with the new value in the column.
✗ Incorrect
The replace() method substitutes all occurrences of 'banana' with 'orange' in the 'Fruit' column. Other values remain unchanged.
❓ data_output
intermediate1:30remaining
Number of replacements made by replace()
Given this DataFrame and code, how many values are replaced?
Data Analysis Python
import pandas as pd df = pd.DataFrame({'Color': ['red', 'blue', 'green', 'blue', 'yellow']}) replaced_df = df.replace({'blue': 'cyan'}) count_replaced = (df['Color'] != replaced_df['Color']).sum() print(count_replaced)
Attempts:
2 left
💡 Hint
Count how many 'blue' values are in the original column.
✗ Incorrect
There are two 'blue' entries in the 'Color' column, both replaced by 'cyan', so the count is 2.
🔧 Debug
advanced2:00remaining
Identify the error in replace() usage
What error does this code raise?
Data Analysis Python
import pandas as pd df = pd.DataFrame({'Animal': ['cat', 'dog', 'bird']}) df['Animal'] = df['Animal'].replace(['cat', 'dog'], 'fish', inplace=True) print(df)
Attempts:
2 left
💡 Hint
Check what replace() returns when inplace=True is used.
✗ Incorrect
When inplace=True, replace() returns None. Assigning this None back to the column causes the column to become NoneType, leading to AttributeError on print.
🚀 Application
advanced2:00remaining
Replacing multiple values with a dictionary
Which option correctly replaces 'NY' with 'New York' and 'CA' with 'California' in the 'State' column?
Data Analysis Python
import pandas as pd df = pd.DataFrame({'State': ['NY', 'CA', 'TX', 'NY', 'FL']}) # Replace code here print(df)
Attempts:
2 left
💡 Hint
Use a dictionary to map old values to new values correctly.
✗ Incorrect
Option D correctly uses a dictionary to replace 'NY' and 'CA' with their full names and assigns the result back to the column.
🧠 Conceptual
expert2:30remaining
Understanding replace() behavior with regex
What is the output of this code?
Data Analysis Python
import pandas as pd df = pd.DataFrame({'Code': ['A1', 'B2', 'C3', 'A4']}) df['Code'] = df['Code'].replace(to_replace='A.', value='Z', regex=True) print(df)
Attempts:
2 left
💡 Hint
The regex 'A.' matches any string starting with 'A' followed by any character.
✗ Incorrect
The regex replaces any string starting with 'A' and one character with 'Z'. So 'A1' and 'A4' become 'Z'. Others remain unchanged.