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
?
It appears you want to use tile()
C = np.concatenate((A, np.tile(B,n)))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With