Modify multiple elements of a Numpy ndarray with ravel_multi_index
Indexing a multi-dimensional Numpy array Accessing a multi-dimensional Numpy array by indices is useful for many tasks, such as parsing the contours in a DICOM-RTSTRUCT file. As a simple example, we are given a 5 x 6 array arr, and a list of the coordinates of 3 points coords: >>> import numpy as np >>> arr = np.arange(30).reshape(5,6) >>> coords = np.array([[0, 1], [3, 4], [3, 2]]) >>> arr array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29]]) >>> coords array([[0, 1], [3, 4], [3, 2]]) To obtain the values of the targeted pixels as a list [arr[0,1], arr[3,4], arr[3,2]], that is [1, 22, 20], it is tempting to write “arr[coords]”.