Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append n copies of an array at the end of a numpy array

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 ?

like image 920
Basj Avatar asked Sep 08 '25 07:09

Basj


2 Answers

It appears you want to use tile()

C = np.concatenate((A, np.tile(B,n)))
like image 145
Craig J Copi Avatar answered Sep 09 '25 22:09

Craig J Copi


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.

like image 36
Daniel Avatar answered Sep 09 '25 22:09

Daniel