1

Say I have the size (2,3,2) array a and the size (2) array b below.

import numpy as np

a = np.array([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
b = np.array([0.2, 0.8])

Array a looks like this:

array a

I'd like to use numpy routines to concatenate b to the first row of each 2d arrray in a to make the array

b array

I can't seem to make concatenate, vstack, append, etc. work.

2 Answers 2

2

Try this:

np.concatenate(([[b]]*2,a),axis=1)
# Result:
array([[[  0.2,   0.8],
        [  1. ,   2. ],
        [  3. ,   4. ],
        [  5. ,   6. ]],

       [[  0.2,   0.8],
        [  7. ,   8. ],
        [  9. ,  10. ],
        [ 11. ,  12. ]]])
Sign up to request clarification or add additional context in comments.

Comments

1

This works:

np.insert(a.astype(float), 0, b, 1)

Output:

array([[[  0.2,   0.8],
        [  1. ,   2. ],
        [  3. ,   4. ],
        [  5. ,   6. ]],

       [[  0.2,   0.8],
        [  7. ,   8. ],
        [  9. ,  10. ],
        [ 11. ,  12. ]]])

If you don't cast with astype() first, you just end up prepending [0, 0]

Note, this is slower than the concatenate():

$ python test.py
m1: 8.20246601105 sec
m2: 43.8010189533 sec

Code:

#!/usr/bin/python

import numpy as np
import timeit

a = np.array([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
b = np.array([0.2, 0.8])

def m1():
    np.concatenate(([[b]]*2,a),axis=1)

def m2():
    np.insert(a.astype(float), 0, b, 1)

print "m1: %s sec" % timeit.timeit(m1)
print "m2: %s sec"  % timeit.timeit(m2)

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.