Search code examples
pythonarraysnumpysynchronize

How to synchronize two arrays with different length?


let's consider two arrays containing indices:

x = [0,1,2,3,4,5...]
y = [0,3,6,9,12,...]

These arrays may have slightly different length, approximately up to 3 indices. In this example let's assume that len(x) = len(y) - 1 I want to return synchronized x, which will be extended by that 1 entry so that these arrays still correspond to each other (x[n]=y[n]+3). I came up with idea to use the np.searchsorted method, however it does not work:

def synchronize_array(self, arr: np.ndarray) -> np.ndarray:
    sync_idx = np.searchsorted(arr, BASE_ARR)
    sync_idx[sync_idx >= len(arr)] = len(arr) - 1
    return arr[sync_idx]

Sync_idx in this case are [0, n-1, n-1, n-1, ...] Is there any approach which will make it possible to synchronize these arrays?


Solution

  • It is not clear what you mean by synchronized, but you can iterate over both of the arrays, filling the shortest with a default value with itertools.zip_longest

    from itertools import zip_longest
    
    x = [0, 1, 2, 3, 4, 5]
    y = [0, 3, 6, 9, 12]
    
    xy = zip_longest(x, y, fillvalue=0)
    print(list(xy))
    

    Which produces

    [(0, 0), (1, 3), (2, 6), (3, 9), (4, 12), (5, 0)]
    

    Cheers!