1

I'm looking for a fast way to take a numpy array, such as [[1,2,3,4]] and turn it into an extended version of itself with its elements repeated N times. I.E. if N = 2, then [[1,2,3,4]] -> [[1,1,2,2,3,3,4,4]]

Obviously I can brute force it with an explicit for, but I'm wondering if this can be vectorized somehow to speed it up?

edit: i'm using [[1,2,3,4]] as shorthand for np.array([1,2,3,4]), sorry for the confusion. Also, thanks to those of you who mentioned np.repeat! That's just what I needed.

1 Answers1

2

Try this:

from numpy import repeat

x = [[1,2,3,4]]
N = 3
y = repeat(x, N).reshape((1,-1))

print(y)

Edit: Quang's solution is shorter, I admit ...

y = repeat(x, N, axis=-1)
Dr. V
  • 1,747
  • 1
  • 11
  • 14