Select N evenly spaced out elements in array, including first and last

To get a list of evenly spaced indices, use np.linspace:

idx = np.round(np.linspace(0, len(arr) - 1, numElems)).astype(int)

Next, index back into arr to get the corresponding values:

arr[idx]

Always use rounding before casting to integers. Internally, linspace calls astype when the dtype argument is provided. Therefore, this method is NOT equivalent to:

# this simply truncates the non-integer part
idx = np.linspace(0, len(array) - 1, numElems).astype(int)
idx = np.linspace(0, len(arr) - 1, numElems, dtype="int")

Leave a Comment

tech