Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat a NumPy array in multiple dimensions at once?

Tags:

python

numpy

np.repeat(np.repeat([[1, 2, 3]], 3, axis=0), 3, axis=1)

works as expected and produces

array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

However,

np.repeat([[1, 2, 3]], [3, 3])

and

np.repeat([[1, 2, 3]], [3, 3], axis=0)

produce errors.

Is it possible to repeat an array in multiple dimensions at once?

like image 279
MWB Avatar asked Oct 29 '22 01:10

MWB


1 Answers

First off, I think the original method you propose is totally fine. It's readable, it makes sense, and it's not very slow.

You could use the repeat method instead of function which reads a bit more nicely:

>>> x.repeat(3, 1).repeat(3, 0)
array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

With numpy's broadcasting rules, there's likely dozens of ways to create the repeated data and throw it around into the shape you want, too. One approach could be to use np.broadcast_to() and repeat the data in D+1 dimensions, where D is the dimension you need, and then collapse it down to D.

For example:

>>> x = np.array([[1, 2, 3]])
>>> np.broadcast_to(x.T, (3, 3, 3)).reshape((3, 9))
array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

And without reshaping (so that you don't need to know the final length):

>>> np.hstack(np.broadcast_to(x, (3, 3, 3)).T)
array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

And there's likely a dozen other ways to do this. But I still think your original version is more idiomatic, as throwing it into extra dimensions to collapse it down is weird.

like image 159
alkasm Avatar answered Nov 15 '22 05:11

alkasm