D. TypeError because astype() cannot convert strings
Solution
Step 1: Identify data in column 'B'
Column 'B' contains strings '10', '20', and 'thirty'. 'thirty' is not numeric.
Step 2: Understand astype(int) behavior
Trying to convert 'thirty' to int causes a ValueError because it cannot be parsed as a number.
Final Answer:
ValueError due to non-numeric string 'thirty' -> Option A
Quick Check:
Non-numeric string causes ValueError = B [OK]
Hint: Non-numeric strings cause ValueError on astype(int) [OK]
Common Mistakes:
Assuming astype silently converts all strings
Confusing ValueError with SyntaxError
Thinking astype() can convert any string
5. You have a DataFrame df with a column 'score' containing float values as strings like '85.5'. You want to convert this column to numeric floats but also handle any non-numeric values by replacing them with 0.0. Which code correctly does this?
hard
A. df['score'] = df['score'].convert(float, fill=0.0)
B. df['score'] = df['score'].astype(float).fillna(0.0)
C. df['score'] = df['score'].astype(int).fillna(0)
D. df['score'] = pd.to_numeric(df['score'], errors='coerce').fillna(0.0)
Solution
Step 1: Understand the problem with astype()
Using astype(float) fails if there are non-numeric strings, causing errors.
Step 2: Use pd.to_numeric() with error handling
pd.to_numeric() with errors='coerce' converts invalid values to NaN, which can be replaced by fillna(0.0).
Step 3: Check other options
df['score'] = df['score'].astype(float).fillna(0.0) does not handle errors properly; df['score'] = df['score'].astype(int).fillna(0) converts to int, losing decimals; df['score'] = df['score'].convert(float, fill=0.0) uses a non-existent method.
Final Answer:
df['score'] = pd.to_numeric(df['score'], errors='coerce').fillna(0.0) -> Option D
Quick Check:
Use pd.to_numeric with errors='coerce' + fillna = A [OK]
Hint: Use pd.to_numeric with errors='coerce' to handle bad data [OK]
Common Mistakes:
Using astype(float) without error handling
Trying to convert to int losing decimals
Using non-existent methods like convert()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.