Choose m evenly spaced elements from a sequence of length n

后端 未结 5 1482
再見小時候
再見小時候 2020-12-09 12:24

I have a vector/array of n elements. I want to choose m elements.

The choices must be fair / deterministic -- equally many from each subsection.

With m=10, n

5条回答
  •  被撕碎了的回忆
    2020-12-09 13:23

    This will always select the first and last elements:

    which_idxs = lambda m, n: np.rint( np.linspace( 1, n, min(m,n) ) - 1 ).astype(int)
    
    evenly_spaced = np.array( your_list )[which_idxs(m,n)]
    

    This will only select a maximum of n elements, in case m is higher than n.

    If you truly want it equally spread throughout the array, even at the ends, then it would be this instead:

    which_idxs = lambda m, n: [idx for idx in np.rint( np.linspace( 1-n/(2*min(m,n)), n+n/(2*min(m,n)), min(m,n)+2 ) - 1 ).astype(int) if idx in range(n)]
    
    evenly_spaced = np.array( your_list )[which_idxs(m,n)]
    

    Which gives you something like this:

    >>> np.array( [1, 2, 3, 'a', 'b', 'c'] )[which_idxs(m,n)]
    Out: array(['2', 'b'])
    

提交回复
热议问题