2

I'd like to duplicate each line of an array N times. Is there a quick way to do so?

Example (N=3):

# INPUT
a=np.arange(9).reshape(3,3)
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
# OUTPUT 
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8],
       [6, 7, 8],
       [6, 7, 8]])
2
  • "duplicate", not "multiply", perhaps? Commented Sep 2, 2013 at 11:40
  • Indeed. I edited my phrasing. Commented Sep 2, 2013 at 11:41

2 Answers 2

3

This is a job for np.repeat:

np.repeat(a,3,axis=0)
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8],
       [6, 7, 8],
       [6, 7, 8]])

Note that this is much faster then the other method.

N=100
%timeit np.repeat(a,N,axis=0)
100000 loops, best of 3: 4.6 us per loop

%timeit rows, cols = a.shape;b=np.hstack(N*(a,));b.reshape(N*rows, cols)
1000 loops, best of 3: 257 us per loop

N=100000
%timeit np.repeat(a,N,axis=0)
100 loops, best of 3: 3.93 ms per loop

%timeit rows, cols = a.shape;b=np.hstack(N*(a,));b.reshape(N*rows, cols)
1 loops, best of 3: 245 ms per loop

Also np.tile is useful in similar situations.

Sign up to request clarification or add additional context in comments.

Comments

1
>>> N = 3
>>> rows, cols = a.shape
>>> b=np.hstack(N*(a,))
>>> b
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8]])
>>> b.reshape(N*rows, cols)
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8],
       [6, 7, 8],
       [6, 7, 8]])

1 Comment

Awesome, but what about big N. If i have N=1000 is it possible to generate such a tuple (a,a,a,...) automatically?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.