Bird
0
0

Which code correctly does this?

hard📝 Application Q15 of 15
NumPy - Array Data Types
You have a numpy array z = np.array([1+1j, 0+0j, -1-1j], dtype=np.complex128). You want to create a new array that contains the magnitudes but replaces zeros with the string 'zero'. Which code correctly does this?
Anp.array([str(m) if m == 0 else m for m in np.abs(z)])
Bnp.abs(z).replace(0, 'zero')
Cnp.where(np.abs(z) == 0, 'zero', np.abs(z))
Dnp.abs(z).astype(str).replace('0.0', 'zero')
Step-by-Step Solution
Solution:
  1. Step 1: Calculate magnitudes with np.abs

    np.abs(z) returns an array of magnitudes as floats.
  2. Step 2: Replace zeros with 'zero' using np.where

    np.where(condition, value_if_true, value_if_false) replaces elements where magnitude is 0 with string 'zero', else keeps magnitude.
  3. Final Answer:

    np.where(np.abs(z) == 0, 'zero', np.abs(z)) -> Option C
  4. Quick Check:

    Use np.where for conditional replacement in arrays [OK]
Quick Trick: Use np.where(condition, 'zero', values) for replacements [OK]
Common Mistakes:
  • Trying to use .replace on numpy arrays (not supported)
  • Converting all to strings unnecessarily
  • Using list comprehension without numpy benefits

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes