[Python] Tracking original indices for rearranged arrays

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Given two numpy arrays of equal shape, I want to track how elements from the first array have moved in the second array. Specifically, for each element in the second array, I want to find its original position in the first array.

    Example 1: All elements present

    a1 = np.array([1, 2, 3, 4]) # original array
    a2 = np.array([2, 1, 3, 4]) # new array

    # Result: [1, 0, 2, 3]
    # Explanation:
    # - 2 was originally at index 1
    # - 1 was originally at index 0
    # - 3 was originally at index 2
    # - 4 was originally at index 3


    Example 2: With new elements

    a1 = np.array([1, 2, 3, 4])
    a2 = np.array([2, 1, 33, 4])

    # Result: [1, 0, -1, 3]
    # The value 33 wasn't in the original array, so it gets -1


    My solution is:

    [a1.tolist().index(v) if v in a1 else -1 for v in a2]


    or np.where(a2[:, None] == a1)[1] but this will not work in example 2

    Is there a better way to do this? In real life my arrays have million of rows. Columns not that many, less than 10.

    Edit: Arrays are not sorted

    Continue reading...

Compartilhe esta Página