NumPy Boolean Array Indexing: Difference between revisions
Jump to navigation
Jump to search
Line 4: | Line 4: | ||
=Overview= | =Overview= | ||
Boolean indexing is when a boolean array is used to select element from another array with the same shape: | Boolean indexing is when a boolean array is used to select element from another array with the same shape. | ||
Boolean indexing for unidimensional arrays: | |||
<syntaxhighlight lang='py'> | <syntaxhighlight lang='py'> | ||
Line 14: | Line 16: | ||
array(['A', 'D'], dtype='<U1') | array(['A', 'D'], dtype='<U1') | ||
</font> | </font> | ||
Boolean indexing for two-dimensional arrays: | |||
<syntaxhighlight lang='py'> | <syntaxhighlight lang='py'> |
Revision as of 16:44, 21 May 2024
Internal
Overview
Boolean indexing is when a boolean array is used to select element from another array with the same shape.
Boolean indexing for unidimensional arrays:
a = np.array(['A', 'B', 'C', 'D'])
b = np.array([True, False, False, True])
a[b]
array(['A', 'D'], dtype='<U1')
Boolean indexing for two-dimensional arrays:
a = np.array([['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H']])
b = np.array([[True, False, True, False], [False, True, False, True]])
array([['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H']], dtype='<U1') array([[ True, False, True, False], [False, True, False, True]])
a[b]
array(['A', 'C', 'F', 'H'], dtype='<U1')
Why did a two dimensional array turn into one-dimensional array?
If the boolean array and the target array do not have the same shape, the operation produces an IndexError
:
IndexError: boolean index did not match indexed array along dimension 0; dimension is 6 but corresponding boolean dimension is 5
The boolean arrays used in boolean indexing can be generated with vectorized comparison.