Bird
Raised Fist0
Pandasdata~20 mins

replace() for value substitution in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Replace Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of replace() with dictionary mapping
What is the output of the following code snippet using pandas replace() method with a dictionary for value substitution?
Pandas
import pandas as pd

df = pd.DataFrame({'Fruit': ['apple', 'banana', 'cherry', 'date']})
result = df.replace({'Fruit': {'banana': 'blueberry', 'date': 'dragonfruit'}})
print(result)
A{'Fruit': ['apple', 'blueberry', 'cherry', 'dragonfruit']}
B{'Fruit': ['apple', 'banana', 'cherry', 'date']}
CKeyError
D{'Fruit': ['blueberry', 'banana', 'dragonfruit', 'date']}
Attempts:
2 left
💡 Hint
Think about how replace() uses the dictionary to map old values to new ones only where specified.
❓ data_output
intermediate
1:30remaining
Number of replaced values in DataFrame
After running the code below, how many values in the DataFrame will be replaced?
Pandas
import pandas as pd

df = pd.DataFrame({'Color': ['red', 'blue', 'green', 'blue', 'yellow']})
new_df = df.replace({'Color': {'blue': 'cyan', 'yellow': 'magenta'}})
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Count how many times the values to be replaced appear in the column.
🔧 Debug
advanced
1:30remaining
Identify the error in replace() usage
What error will this code raise when trying to replace values in a pandas DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3]})
# Incorrect replace usage
result = df.replace(1, {2: 20})
AKeyError
BValueError
CTypeError
DNo error, runs successfully
Attempts:
2 left
💡 Hint
Check the expected argument types for replace() method.
🚀 Application
advanced
2:00remaining
Using replace() to clean categorical data
You have a DataFrame with a column 'Status' containing values 'yes', 'no', 'n/a', and 'unknown'. You want to replace 'n/a' and 'unknown' with NaN for analysis. Which code snippet correctly does this?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame({'Status': ['yes', 'no', 'n/a', 'unknown', 'yes']})
Adf.replace({'Status': {'n/a': np.nan, 'unknown': np.nan}})
Bdf.replace({'Status': ['n/a', 'unknown'], np.nan})
Cdf.replace(['n/a', 'unknown'], np.nan, inplace=True)
Ddf.replace({'n/a': np.nan, 'unknown': np.nan})
Attempts:
2 left
💡 Hint
Use a dictionary mapping column name to another dictionary of old to new values.
🧠 Conceptual
expert
2:30remaining
Behavior of replace() with regex=true
Given the DataFrame below, what will be the output after applying replace() with regex=true?
Pandas
import pandas as pd

df = pd.DataFrame({'Code': ['abc123', 'def456', 'ghi789']})
result = df.replace({'Code': r'\d+'}, 'NUM', regex=True)
print(result)
A{'Code': ['NUM123', 'NUM456', 'NUM789']}
BTypeError
C{'Code': ['abc123', 'def456', 'ghi789']}
D{'Code': ['abcNUM', 'defNUM', 'ghiNUM']}
Attempts:
2 left
💡 Hint
regex=true allows pattern matching and replacement inside strings.

Practice

(1/5)
1. What does the replace() method do in pandas?
easy
A. It sorts the DataFrame based on column values.
B. It deletes rows containing specific values.
C. It adds new columns to the DataFrame.
D. It swaps specified values in a DataFrame or Series with new values.

Solution

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

    The replace() method is used to change specific values in pandas data structures.
  2. Step 2: Compare with other options

    The other options describe sorting the DataFrame, deleting rows, and adding columns, which are unrelated to value substitution.
  3. Final Answer:

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

    replace() = value substitution [OK]
Hint: Remember: replace() swaps old values with new ones [OK]
Common Mistakes:
  • Confusing replace() with drop() or sort_values()
  • Thinking replace() adds or removes rows
  • Assuming replace() changes column names
2. Which of the following is the correct syntax to replace all occurrences of 0 with 100 in a pandas Series s?
easy
A. s.replace([100], [0])
B. s.replace(100, 0)
C. s.replace(0, 100)
D. s.replace({100: 0})

Solution

  1. Step 1: Identify the correct replace() syntax

    The syntax s.replace(old_value, new_value) replaces all old_value with new_value.
  2. Step 2: Check each option

    s.replace(0, 100) correctly replaces 0 with 100. The other options reverse the values: s.replace(100, 0), s.replace([100], [0]), s.replace({100: 0}).
  3. Final Answer:

    s.replace(0, 100) -> Option C
  4. Quick Check:

    replace(old, new) = s.replace(0, 100) [OK]
Hint: Use s.replace(old_value, new_value) for single value swap [OK]
Common Mistakes:
  • Swapping the old and new values by mistake
  • Using dict with reversed keys and values
  • Confusing list syntax with dict syntax
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 2], 'B': [4, 5, 2, 4]})
df_new = df.replace(2, 99)

What is the content of df_new?
medium
A. {'A': [1, 99, 3, 99], 'B': [4, 5, 99, 4]}
B. {'A': [1, 2, 3, 2], 'B': [4, 5, 2, 4]}
C. {'A': [99, 99, 99, 99], 'B': [99, 99, 99, 99]}
D. {'A': [1, 2, 3, 2], 'B': [4, 5, 99, 4]}

Solution

  1. Step 1: Understand replace(2, 99) on DataFrame

    All occurrences of 2 in the DataFrame are replaced by 99.
  2. Step 2: Apply replacement to each column

    Column 'A': 2 replaced by 99 at positions 1 and 3.
    Column 'B': 2 replaced by 99 at position 2.
  3. Final Answer:

    {'A': [1, 99, 3, 99], 'B': [4, 5, 99, 4]} -> Option A
  4. Quick Check:

    All 2s -> 99 in df_new [OK]
Hint: replace() changes all matching values in all columns [OK]
Common Mistakes:
  • Assuming replace only affects one column
  • Thinking original df changes without assignment
  • Replacing only first occurrence instead of all
4. What is wrong with this code snippet?
df = pd.DataFrame({'X': [1, 2, 3]})
df.replace(2, 99)
print(df)

It is intended to replace 2 with 99 in column 'X'.
medium
A. The replace() method does not modify df unless inplace=True or reassigned.
B. The replace() method syntax is incorrect; it needs a dictionary.
C. The print statement should be before replace().
D. replace() cannot be used on DataFrames.

Solution

  1. Step 1: Understand replace() behavior

    By default, replace() returns a new DataFrame and does not change the original unless inplace=True or reassigned.
  2. Step 2: Analyze the code snippet

    The code calls replace() but does not assign the result back to df or use inplace=True, so df remains unchanged.
  3. Final Answer:

    The replace() method does not modify df unless inplace=True or reassigned. -> Option A
  4. Quick Check:

    replace() returns new object unless inplace=True [OK]
Hint: Always assign replace() result or use inplace=True [OK]
Common Mistakes:
  • Expecting replace() to change original without assignment
  • Using wrong syntax for replace()
  • Thinking replace() works only on Series
5. You have a DataFrame:
df = pd.DataFrame({'Grade': ['A', 'B', 'C', 'D', 'F']})

You want to replace grades 'A' and 'B' with 'Pass' and 'C', 'D', 'F' with 'Fail' in one call. Which code does this correctly?
hard
A. df.replace(['A', 'B'], ['Pass', 'Pass']).replace(['C', 'D', 'F'], ['Fail', 'Fail', 'Fail'])
B. df.replace({'A': 'Pass', 'B': 'Pass', 'C': 'Fail', 'D': 'Fail', 'F': 'Fail'})
C. df.replace({'Pass': ['A', 'B'], 'Fail': ['C', 'D', 'F']})
D. df.replace({'A': 'Pass', 'B': 'Fail', 'C': 'Pass', 'D': 'Fail', 'F': 'Pass'})

Solution

  1. Step 1: Understand replace() with dictionary mapping

    Using a dictionary with keys as old values and values as new values allows multiple replacements in one call.
  2. Step 2: Check each option

    df.replace({'A': 'Pass', 'B': 'Pass', 'C': 'Fail', 'D': 'Fail', 'F': 'Fail'}) correctly maps each grade to 'Pass' or 'Fail'. df.replace(['A', 'B'], ['Pass', 'Pass']).replace(['C', 'D', 'F'], ['Fail', 'Fail', 'Fail']) uses two replace calls, which works but is two steps, not one call. df.replace({'Pass': ['A', 'B'], 'Fail': ['C', 'D', 'F']}) reverses keys and values, which is invalid. df.replace({'A': 'Pass', 'B': 'Fail', 'C': 'Pass', 'D': 'Fail', 'F': 'Pass'}) mixes mappings incorrectly.
  3. Final Answer:

    df.replace({'A': 'Pass', 'B': 'Pass', 'C': 'Fail', 'D': 'Fail', 'F': 'Fail'}) -> Option B
  4. Quick Check:

    Use dict in replace() for multiple value swaps [OK]
Hint: Use dict with old:new pairs for multiple replacements [OK]
Common Mistakes:
  • Using lists instead of dict for multiple replacements
  • Reversing keys and values in dict
  • Chaining replace() unnecessarily
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