Repeat arrow on new axis along new axis

What's the best / most efficient way?

where x is an array and n is the number of times I want to repeat:

np.repeat(x[None,...], n, axis=0)

      

or

ones = [1] * len(x.shape)
np.tile(x, tuple(n, *ones))

      

note that for a known size of the array, the latter becomes simple:

np.tile(x, (n, 1, 1))  # x is 2D

      

+3


source to share


1 answer


Part of the code for np.tile

:

for i, nrep in enumerate(tup):
    if nrep!=1:
        c = c.reshape(-1, n).repeat(nrep, 0)

      

In other words, it repeat

has more than 1 repetition on each axis. It is, an effect, generalization repeat

to multiple axes.

Thus, I would expect the timings to be similar, although a simpler repeat

would have less Python overhead. repeat

compiled. (a few simple tests confirm this - repeat

2x faster for small arrays, slightly faster for large ones).

ps The step is x[None,...]

practically cost-free. And because of the broadcast, that might be all you need.


pss There is an even faster way to do this repetition using np.lib.index_tricks.as_strided

. For (20,50)

x

<,



as_strided(x,shape=(n,20,50),strides=(0,200,4))

      

np.broadcast_arrays

also uses as_strided

. So this gives the same thing:

np.broadcast_arrays(np.ones((n,1,1)),x)[1] 

      

But to be honest, this is just a broadcast development, not a real replay. The data has not been replicated. The same values ​​are used only n

once.

Broadcast can be used to populate a full array, but the timings are the same as for repeat

. This could be what it repeat

does under the hood.

z = np.empty((300,20,50),dtype=int)
z[:] = x[None,...]

      

+6


source







All Articles