[Python] Expanding pandas based code that detect the frequency of the consecutive number to...

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    This stackoverflow answer provides a simple way (below) to find the frequency and indices of consecutive repeated numbers. This solution is much faster than loop-based code (see the original post above).

    boundaries = np.where(np.diff(aa) != 0)[0] + 1 #group boundaries

    get_idx_freqs = lambda i, d: (np.concatenate(([0], i))[d >= 2], d[d >= 2])
    idx, freqs = get_idx_freqs(boundaries, np.diff(np.r_[0, boundaries, len(aa)]))


    and the output

    # aa=np.array([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
    (array([ 1, 3, 6, 10]), array([2, 3, 4, 5]))

    # aa=np.array([1,1,1,np.nan,np.nan,1,1,np.nan])
    (array([0, 5]), array([3, 2]))


    Wondering if this solution could be expanded to work on multidimensional array instead of the slow traditional loop.

    Continue reading...

Compartilhe esta Página