Is there a method to resize/reshape an NumPy array that will preserve the sum() of each row

Viewed 170

reshape/resize don't seem to provide the functionality I'm looking for.

In the simplest case, I want to add two 1D arrays with different numbers of columns, but each represents the same period. For example, each array contains data for 1 hour. 1 array sampling rate is 15 minutes the other is 30 minutes.

array1 = numpy.array([4, 4, 4, 4])    # 4 samples per hour (every 15 minutes)
array2 = numpy.array([5, 5])          # 2 samples per hour (every 30 minutes)

The desired result is to "scale" array1 to the same size as array2 then add.

scaled_array1 = [8, 8]                # array1 scaled now has 2 samples per hour

array3 = scaled_array1 + array2       # [13, 13]

Alternatively, scale array 2 to 4 samples per hour:

scaled_array2 = [2.5, 2.5, 2.5, 2.5]
array3 = array1 + scaled_array2       # [6.5, 6.5, 6.5, 6.5]

I could write a class to do this, but it seems there must be an existing function that would provide this functionality? I've read through all of the array manipulation routines in the NumPy docs, but none seem to fit.

1 Answers

You can perform those operations by computing the 'scaling' factor between the two arrays and applying either np.repeat or np.reshape. The factor is given by

>>> factor = len(array1)//len(array2)
2
  • Upsampling array2->array1's size. We repeat the elements in array2 to match the size of array1, then normalize appropriately:

    >>> np.repeat(array2, factor) / factor
    array([2.5, 2.5, 2.5, 2.5])
    
  • Downsampling array1->array2's size. We can reshape the array and reduce the dimension by summing:

    >>> array1.reshape(*array2.shape, -1).sum(1)
    array([8, 8])
    
Related