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

前端 未结 3 1783
无人及你
无人及你 2021-01-01 20:34

I have an array of arbitrary length, and I want to select N elements of it, evenly spaced out (approximately, as N may be even, array length may be prime, etc) that includes

3条回答
  •  再見小時候
    2021-01-01 21:35

    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')
    

提交回复
热议问题