Skip to content Skip to sidebar Skip to footer

Arbitrary N-dimensional Repeat Of N-dimensional Numpy Array

Say you have the following N-dimensional array >>> import numpy as np >>> Z = np.array(7*[6*[5*[4*[3*[range(2)]]]]]) >>> Z.ndim 6 Note that N = 6, but I

Solution 1:

mean has a keepdims parameter the retains the compressed dimension:

In [139]: shape=(2,3,4,5)
In [140]: x=np.arange(np.prod(shape)).reshape(shape)
In [141]: m=x.mean(axis=2, keepdims=True)
In [142]: m.shape
Out[142]: (2, 3, 1, 5)

It's easy now to replicate m along that dimension:

In [144]: m1=np.broadcast_to(m,shape)
In [145]: m1.shape
Out[145]: (2, 3, 4, 5)

repeat and tile are also handy means of replicating an array along a dimension.

broadcast_to expands the array without adding elements, just by changing shape and strides:

In [146]: m1.strides
Out[146]: (120, 40, 0, 8)

repeat increases the size of the array:

In [148]: m2=np.repeat(m, shape[2], axis=2)
In [149]: m2.shape
Out[149]: (2, 3, 4, 5)
In [150]: m2.strides
Out[150]: (480, 160, 40, 8)

m could be used without either, as in x-m. m broadcasts with x here.


Post a Comment for "Arbitrary N-dimensional Repeat Of N-dimensional Numpy Array"