[Python] Finding shifts required between two arrays elements

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have two arrays, and I am trying to find the displacement for each elements to make them match. An example:

    a = np.array([1, 0, 2, 0, 0, 1, 0, 2, 0, 0, 1, 0, 2, 0, 0 ] )
    b = np.array([2, 0, 0, 1, 0, 2, 0, 0, 1, 0, 2, 0, 0, 1, 0] )

    # expected
    c = np.array ([3, 0, 2, 1, 0, 2, 0, 2, 1, 0, 2, 0,2, 1, 0 ])



    The expected results, in array a, the first element is 1, and the closest match in b is 3 steps away. The second element in a is 0 and it is a match in b so zero steps away. The third element is 2, and the closes in b is b[0] which is 2 steps away from a[2]=2 .. and so on.

    I tried to come up with a function to solve this:

    def find_shifts_required(x, y):
    assert len(x) == len(y)
    result = np.zeros(len(x))
    labels = np.unique(x)

    for lbl in labels:
    x_pos = np.where(x == lbl)
    y_pos = np.where(y == lbl) #.min())
    result[x_pos] = np.subtract(x_pos , y_pos )
    _shifts = np.absolute(result).astype(int)
    return _shifts

    d = find_shifts_required(a,b)

    print("expected: " , c)
    print("actual: " , d)



    Which gives me:

    expected: [3 0 2 1 0 2 0 2 1 0 2 0 2 1 0]
    actual: [3 0 2 1 0 3 0 2 1 0 3 0 2 1 0]


    I am wondering if this problem has been solved somewhere (scipy: I wasn't able to find a name) or a better implementation is available.

    By better I mean a working solution, as this one does not give the correct results. A simpler, faster will be great.

    Continue reading...

Compartilhe esta Página