0
0
NumPydata~5 mins

Boolean indexing in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is Boolean indexing in numpy?
Boolean indexing is a way to select elements from a numpy array using a condition that returns True or False for each element. Only elements where the condition is True are selected.
Click to reveal answer
beginner
How do you create a Boolean array for indexing?
You create a Boolean array by applying a condition to a numpy array, for example: arr > 5 returns True for elements greater than 5 and False otherwise.
Click to reveal answer
beginner
Example: Select all elements greater than 10 from array arr = np.array([5, 12, 7, 15])
Use Boolean indexing: arr[arr > 10] returns array([12, 15]) because only 12 and 15 are greater than 10.
Click to reveal answer
intermediate
Can Boolean indexing be used to modify elements in a numpy array?
Yes, you can use Boolean indexing to select elements and assign new values. For example, arr[arr < 5] = 0 sets all elements less than 5 to zero.
Click to reveal answer
intermediate
What happens if the Boolean array has a different shape than the original array?
The Boolean array must have the same shape as the original array for Boolean indexing to work. Otherwise, numpy will raise a ValueError.
Click to reveal answer
What does arr[arr > 3] do if arr = np.array([1, 4, 3, 6])?
AReturns the original array
BSelects elements greater than 3
CSelects elements equal to 3
DSelects elements less than 3
Which of these is a valid Boolean indexing expression?
Aarr[arr == 5]
Barr[5]
Carr["5"]
Darr[5 > arr]
What type of array is needed for Boolean indexing?
ABoolean array
BFloat array
CInteger array
DString array
If arr = np.array([2, 8, 5]), what does arr[arr < 5] = 0 do?
ADeletes elements less than 5
BSets elements greater than 5 to zero
CRaises an error
DSets elements less than 5 to zero
What error occurs if Boolean array shape does not match original array?
AIndexError
BTypeError
CValueError
DKeyError
Explain how Boolean indexing works in numpy with an example.
Think about how True/False values select elements.
You got /4 concepts.
    Describe how you can use Boolean indexing to modify elements in a numpy array.
    Consider changing values where condition is True.
    You got /3 concepts.