4

Let A and B be two numpy arrays.

I want to append n copies of B at the end of A :

C = [A, B, B, B, ... (n times) ... B, B]

How to do this simply/efficiently with numpy ?

Something like

numpy.append(A, [B * n])        # B * n  is not n copies of B,
                                #      but rather B multiplied by constant n ?

or with numpy.concatenate ?

1
  • Remark : In fact in my code B is a view from A (B = A[-1000:] ) but I don't think this will be important here, it should work in a more general case for which B is any array. Commented Feb 20, 2014 at 23:43

2 Answers 2

8

It appears you want to use tile()

C = np.concatenate((A, np.tile(B,n)))
Sign up to request clarification or add additional context in comments.

Comments

1

First lets check out concatenate routines:

A = np.arange(1E4)
#Baseline
%timeit np.concatenate((A,A))
100000 loops, best of 3: 11.1 µs per loop

%timeit np.hstack((A,A))
10000 loops, best of 3: 20.9 µs per loop

%timeit np.append(A,A)
100000 loops, best of 3: 19 µs per loop

Note that this is only the case for small arrays, append, hstack, and concatenate should be asymptotically convergent as all of these functions call concatenate, the main difference is python overhead. Now the only question is how to create array B:

#Using python
%timeit np.concatenate((A,[5]*10000))
1000 loops, best of 3: 1.1 ms per loop

#Tile small array
%timeit C = np.concatenate((A, np.tile(np.array(5),1E4)))
10000 loops, best of 3: 92.1 µs per loop

#Create an array of ones and multiply by a number
%timeit np.concatenate((A,np.ones(1E4)*5))
10000 loops, best of 3: 39.5 µs per loop

#Create empty array and fill from A and then set
%timeit C = np.empty(2E4); C[:10000]=A; C[10000:]=5
100000 loops, best of 3: 16.8 µs per loop

Looks like our winner is: create an empty array and then set the elements. This is assuming a certain array size, but most of these should scale similarly.

Comments

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.