restride

Contents

restride#

restride(arr, binfactor, squeezed=True, flattened=False)[source]#

Restride an N-D array into bins, without copying.

Let arr.shape = (s1, s2, ...) and binfactor = (b1, b2, ...) (same length), the new shape will be (s1/b1, s2/b2, ..., b1, b2, ...) (squeezed).

Parameters:
  • arr (numpy.ndarray) – Input array. Each s_i must be a multiple of the corresponding b_i.

  • binfactor (int or tuple of int) – Bin factor. If an integer, it is used for all axes. If its length is lower than arr.ndim, it is prepended with 1’s.

  • squeezed (bool, optional) – Remove the length-1 axes from the output. Default is True.

  • flattened (bool, optional) – Flatten the bin axes into a single axis. Note that this will probably induce a copy of the array. Default is False.

Returns:

numpy.ndarray – Restrided view of arr, of shape (s1/b1, s2/b2, ..., b1, b2, ...).

Raises:

AssertionError – If binfactor is incompatible with the shape of arr.

Examples

Bin 2D-array by a factor 2:

>>> restride(np.ones((6, 8)), 2).shape
(3, 4, 2, 2)

Bin 2D-array by a factor 2, with flattening of the last 2 bin axes:

>>> restride(np.ones((6, 8)), 2, flattened=True).shape
(3, 4, 4)

Bin 2D-array by uneven factor (3, 2):

>>> restride(np.ones((6, 8)), (3, 2)).shape
(2, 4, 3, 2)

Bin 3D-array by factor 2 over the last 2 axes, and take bin average:

>>> q = np.arange(2*4*6).reshape(2, 4, 6)
>>> restride(q, (2, 2)).mean(axis=(-1, -2))
array([[[ 3.5,  5.5,  7.5],
        [15.5, 17.5, 19.5]],

       [[27.5, 29.5, 31.5],
        [39.5, 41.5, 43.5]]])

Bin 3D-array by factor 2, and take bin average:

>>> restride(q, 2).mean(axis=(-1, -2, -3))
array([[15.5, 17.5, 19.5],
       [27.5, 29.5, 31.5]])