Bird
Raised Fist0
Data Analysis Pythondata~20 mins

replace() for value substitution in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Replace Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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)
A
     Fruit
0    apple
1   orange
2   cherry
3   orange
4    apple
B
     Fruit
0    apple
1   banana
2   cherry
3   banana
4    apple
C
     Fruit
0    apple
1   orange
2   cherry
3   banana
4    apple
D
     Fruit
0    apple
1   orange
2   orange
3   orange
4    apple
Attempts:
2 left
💡 Hint
replace() changes all exact matches of the old value with the new value in the column.
❓ data_output
intermediate
1: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)
A3
B1
C2
D0
Attempts:
2 left
💡 Hint
Count how many 'blue' values are in the original column.
🔧 Debug
advanced
2: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)
AAttributeError: 'NoneType' object has no attribute 'replace'
BTypeError: replace() got an unexpected keyword argument 'inplace'
CValueError: Length of replacement does not match length of values
DNo error, prints DataFrame with 'cat' and 'dog' replaced by 'fish'
Attempts:
2 left
💡 Hint
Check what replace() returns when inplace=True is used.
🚀 Application
advanced
2: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)
Adf['State'] = df['State'].replace({'NY': 'California', 'CA': 'New York'})
Bdf['State'].replace(['NY', 'CA'], ['New York', 'California'])
Cdf['State'] = df['State'].replace(['NY', 'CA'], ['New York', 'California'])
Ddf['State'] = df['State'].replace({'NY': 'New York', 'CA': 'California'})
Attempts:
2 left
💡 Hint
Use a dictionary to map old values to new values correctly.
🧠 Conceptual
expert
2: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)
A
  Code
0   Z1
1   B2
2   C3
3   Z4
B
  Code
0    Z
1   B2
2   C3
3    Z
C
  Code
0   A1
1   B2
2   C3
3   A4
D
  Code
0   Z
1   Z
2   Z
3   Z
Attempts:
2 left
💡 Hint
The regex 'A.' matches any string starting with 'A' followed by any character.

Practice

(1/5)
1. What does the replace() function do in data analysis with pandas?
easy
A. It sorts the DataFrame based on column values.
B. It deletes rows containing specific values.
C. It substitutes specified values in a DataFrame or Series with new values.
D. It calculates the mean of numeric columns.

Solution

  1. Step 1: Understand the purpose of replace()

    The replace() function is used to change specific values in data, not to delete or sort data.
  2. Step 2: Match function to description

    Replacing means substituting old values with new ones, which matches It substitutes specified values in a DataFrame or Series with new values.
  3. Final Answer:

    It substitutes specified values in a DataFrame or Series with new values. -> Option C
  4. Quick Check:

    replace() = substitute values [OK]
Hint: Remember: replace() swaps old values with new ones [OK]
Common Mistakes:
  • Confusing replace() with drop() or sort()
  • Thinking replace() deletes data
  • Assuming replace() calculates statistics
2. Which of the following is the correct syntax to replace all occurrences of 0 with 100 in a pandas Series named data?
easy
A. data.replace(0, 100)
B. data.replace(0 => 100)
C. data.replace(0: 100)
D. data.replace(0 == 100)

Solution

  1. Step 1: Recall correct replace() syntax

    The correct syntax uses a comma to separate old and new values: replace(old_value, new_value).
  2. Step 2: Check each option

    Only data.replace(0, 100) uses the correct syntax. Others use invalid operators like =>, :, or ==.
  3. Final Answer:

    data.replace(0, 100) -> Option A
  4. Quick Check:

    replace(old, new) uses comma [OK]
Hint: Use comma between old and new values in replace() [OK]
Common Mistakes:
  • Using arrows or colons instead of commas
  • Confusing replace() with comparison operators
  • Missing parentheses or commas
3. Given the pandas Series data = pd.Series(['apple', 'banana', 'apple', 'cherry']), what is the output of data.replace('apple', 'orange')?
medium
A. 0 orange 1 banana 2 orange 3 cherry dtype: object
B. 0 apple 1 banana 2 apple 3 cherry dtype: object
C. 0 orange 1 orange 2 orange 3 orange dtype: object
D. 0 banana 1 banana 2 banana 3 cherry dtype: object

Solution

  1. Step 1: Identify values to replace

    The code replaces all 'apple' entries with 'orange'. The original Series has 'apple' at index 0 and 2.
  2. Step 2: Replace and check output

    Only positions 0 and 2 change to 'orange'. Others remain the same.
  3. Final Answer:

    0 orange 1 banana 2 orange 3 cherry dtype: object -> Option A
  4. Quick Check:

    Replace 'apple' with 'orange' only [OK]
Hint: Only matching values change, others stay same [OK]
Common Mistakes:
  • Replacing all values instead of only matches
  • Confusing replace() with map() or apply()
  • Expecting in-place change without assignment
4. What is wrong with this code snippet if we want to replace all 1s with 10s in a pandas DataFrame column df['col']?
df['col'].replace(1, 10)
print(df['col'])
medium
A. The print statement should be before replace().
B. The replace() method does not modify df['col'] unless assigned or inplace=True.
C. replace() cannot be used on DataFrame columns.
D. The syntax of replace() is incorrect; it needs a dictionary.

Solution

  1. Step 1: Understand replace() behavior

    By default, replace() returns a new object and does not change the original unless assigned or inplace=True.
  2. Step 2: Identify the issue in code

    The code calls replace() but does not assign the result back, so df['col'] remains unchanged.
  3. Final Answer:

    The replace() method does not modify df['col'] unless assigned or inplace=True. -> Option B
  4. Quick Check:

    Assign or use inplace=True to keep changes [OK]
Hint: Always assign replace() result or use inplace=True [OK]
Common Mistakes:
  • Expecting replace() to change data without assignment
  • Using wrong syntax for replace()
  • Thinking replace() works only on entire DataFrames
5. You have a DataFrame df with a column 'status' containing values: 'old', 'new', 'old', 'pending'. You want to replace 'old' with 'archived' and 'pending' with 'waiting' in one command. Which code correctly does this?
hard
A. df['status'].replace(['old', 'pending'], ['archived', 'waiting'])
B. df['status'].replace('old' => 'archived', 'pending' => 'waiting')
C. df['status'].replace('old', 'archived').replace('pending', 'waiting')
D. df['status'].replace({'old': 'archived', 'pending': 'waiting'}, inplace=True)

Solution

  1. Step 1: Identify multi-value replacement syntax

    To replace multiple values at once, use a dictionary mapping old to new values.
  2. Step 2: Check for inplace modification

    Using inplace=True applies changes directly to the DataFrame column.
  3. Step 3: Evaluate options

    df['status'].replace({'old': 'archived', 'pending': 'waiting'}, inplace=True) uses dictionary and inplace=True correctly. df['status'].replace(['old', 'pending'], ['archived', 'waiting']) returns new Series but does not assign. df['status'].replace('old', 'archived').replace('pending', 'waiting') chains replace but is less efficient. df['status'].replace('old' => 'archived', 'pending' => 'waiting') uses invalid syntax.
  4. Final Answer:

    df['status'].replace({'old': 'archived', 'pending': 'waiting'}, inplace=True) -> Option D
  5. Quick Check:

    Use dict + inplace=True for multiple replacements [OK]
Hint: Use dict and inplace=True for multiple replacements [OK]
Common Mistakes:
  • Using list replacement without assignment
  • Chaining replace() without assignment
  • Using invalid syntax with arrows
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