NumPy Boolean Array Indexing: Difference between revisions

From NovaOrdis Knowledge Base
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:
 
<syntaxhighlight lang='py'>
a = np.array(['A', 'B', 'C', 'D'])
b = np.array([True, False, False, True])
a[b]
</syntaxhighlight>
<font size=-2>
array(['A', 'D'], dtype='<U1')
</font>
 
<syntaxhighlight lang='py'>
a = np.array([['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H']])
b = np.array([[True, False, True, False], [False, True, False, True]])
</syntaxhighlight>
<font size=-2>
array([['A', 'B', 'C', 'D'],
        ['E', 'F', 'G', 'H']], dtype='<U1')
array([[ True, False,  True, False],
        [False,  True, False,  True]])
</font>
<syntaxhighlight lang='py'>
a[b]
</syntaxhighlight>
<font size=-2>
  array(['A', 'C', 'F', 'H'], dtype='<U1')
</font>
<font color=darkkhaki>Why did a two dimensional array turn into one-dimensional array?</font>


If the boolean array and the target array do not have the same shape, the operation produces an <code>IndexError</code>:
If the boolean array and the target array do not have the same shape, the operation produces an <code>IndexError</code>:

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:

a = np.array(['A', 'B', 'C', 'D'])
b = np.array([True, False, False, True])
a[b]

array(['A', 'D'], dtype='<U1')

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.