Fancy Indexing

Arrays created using fancy indexing such as boolean masks or integer arrays, are copies of the original array, not the views.

Using Masks

a = np.arange(10)
sub_array = a[a%2 == 0]
# array([0, 2, 4, 6, 8])

sub_array doesn’t share the same memory buffer with array a.

Using array of Integers

Indexing by providing an array of integers returns the array in the same shape of the given array of integers.

indexes = np.array([[1, 5],
                    [6, 7]])
a[indexes]
# array([[1, 5],
#      [6, 7]])

Results are always copy of the original arrays.

Assigning new values

New values can be assigned using these methods.

 
a[a%2 == 0] = -1
# assigns -1 to all the item divisible by 2
 
a[indexes] = -1
# assigns -1 to all given indexes.

References

  1. https://lectures.scientific-python.org/intro/numpy/array_object.html#fancy-indexing