0
0
NumPydata~5 mins

np.where() for conditional selection in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does np.where() do in numpy?

np.where() helps you pick values from arrays based on a condition. It returns elements chosen from two options depending on whether the condition is true or false.

Click to reveal answer
beginner
How do you use np.where() to replace negative numbers in an array with zero?

You write a condition to check for negative numbers, then tell np.where() to put zero if true, else keep the original number.

np.where(arr < 0, 0, arr)
Click to reveal answer
beginner
What are the three arguments of np.where(condition, x, y)?
  • condition: A test that returns True or False for each element.
  • x: Values to pick when condition is True.
  • y: Values to pick when condition is False.
Click to reveal answer
intermediate
What happens if you use np.where() with only a condition argument?

It returns the indices (positions) where the condition is True, instead of picking values.

Click to reveal answer
beginner
Why is np.where() useful in data science?

It lets you quickly select or change data based on conditions without writing loops. This makes your code faster and easier to read.

Click to reveal answer
What does np.where(arr > 5, 10, 0) do?
AReturns the original array unchanged
BReturns indices where elements are greater than 5
CReplaces elements less than 5 with 10, others with 0
DReplaces elements greater than 5 with 10, others with 0
What does np.where(condition) return if only one argument is given?
AIndices where condition is True
BValues where condition is True
CBoolean array of condition
DError because arguments are missing
Which of these is a correct use of np.where() to replace negative values with zero?
Anp.where(arr, 0, arr)
Bnp.where(arr &gt; 0, arr, 0)
Cnp.where(arr &lt; 0, 0, arr)
Dnp.where(arr == 0, 0, arr)
If arr = np.array([1, 2, 3]), what does np.where(arr > 2) return?
Aarray([False, False, True])
B(array([2]),)
Carray([3])
Darray([1, 2])
Why might np.where() be preferred over a for-loop for conditional selection?
AIt is faster and uses less code
BIt always uses more memory
CIt only works with small arrays
DIt requires writing complex loops
Explain how np.where() can be used to change values in an array based on a condition.
Think about how you pick between two options depending on a test.
You got /4 concepts.
    Describe the difference between using np.where() with one argument versus three arguments.
    Focus on what output you get in each case.
    You got /4 concepts.