Search code examples
pythonbroadcast

Python - Different shapes 1D array broadcasting


I have two arrays of different shapes that I would like to broadcast together:

  • array1: (1460,)
  • array2: (1462,)

Obviously while trying to broadcast array together it returns:

ValueError: operands could not be broadcast together with shapes (1460,) (1462,)

The two array are time series, but array1 is missing the first and last values in comparison with array2.

Does anyone can point me out some tools or solution in order to broadcast together 1D array of different shapes?


Solution

  • I assume you're having numpy arrays, and what you could do to avoid the error is get them to equal length. If you know the indices that are missing, you could very simply write e.g.

    w = np.where(array1 < array2[1:-1])
    

    Note that in this case, the index array returned by np.where refers to array1 and will give a wrong result when applied to array2! To avoid this issue, another hack would be appending np.nan to the shorter array, i.e. where it has no 'corresponding' value in the array you want to compare it to:

    array1 = np.concatenate(([np.nan], array1 , [np.nan]))
    

    then you could do stuff like

    w = np.where(array1 < array2)
    

    with w being applicable to array1 and array2. So I think np.concatenate is a way to go here. Note that this is not a general solution. That would require a more in-depth knowledge of how you came to this issue.