[Python] Cumulative sum of one array in order defined by other array without doing 2 sort...

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

  1. Stack

    Stack Membro Participativo

    I have two numpy arrays:

    import numpy as np
    arr1 = np.array([1,4,2,5,6,3,2])
    arr2 = np.array([1,0,2,4,3,6,5])


    I would like to find the cumulative sum of arr1 according to the order defined in arr2. Expected output:

    array([ 5, 4, 7, 18, 13, 23, 20])


    Here's one way to calculate this:

    sorting_indices = np.argsort(arr2)
    result = np.cumsum(arr1[sorting_indices])[np.argsort(sorting_indices)]


    However, this involves doing two sort/argsort operations (np.argsort(arr2) and then np.argsort(sorting_indices))

    Is it possible to produce the same result, but doing only a single sort or argsort operation?

    Continue reading...

Compartilhe esta Página