6

I.m facing a little issue to combine arrays in a certain manner. Let's say we have

a=array([[1,1,1],[2,2,2],[3,3,3]])

b=array([[10,10,10],[20,20,20],[30,30,30]])

I wish to get

c=array([[[1,1,1],[10,10,10]],[[2,2,2],[20,20,20]],[[3,3,3],[30,30,30]]])

The real issue is that my arrays a and b are much longer than 3 coordinates!

The best I achieved using concatenate is:

concatenate((a,b),axis=2)

which results in

array([[ 1, 1, 1, 10, 10, 10], [ 2, 2, 2, 20, 20, 20], [ 3, 3, 3, 30, 30, 30]])

it is pretty good but not have enough depth.

Also, I've tried something from another question to get the desired depth:

d=concatenate((a[...,None],b[...,None]),axis=2)

but results in:

 array([[[ 1, 10],
    [ 1, 10],
    [ 1, 10]],

   [[ 2, 20],
    [ 2, 20],
    [ 2, 20]],

   [[ 3, 30],
    [ 3, 30],
    [ 3, 30]]])

Which still does not works...

3 Answers 3

6

ummm zip(a,b) ?

is not what you want??

>>> a=array([[1,1,1],[2,2,2],[3,3,3]]);b=array([[10,10,10],[20,20,20],[30,30,30]
>>> zip(a,b)
[(array([1, 1, 1]), array([10, 10, 10])), (array([2, 2, 2]), array([20, 20, 20])), (array([3, 3, 3]), array([30, 30, 30]))]
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I was looking for array(zip(a,b))
If you want the output to be an array, i.e. if you do np.array(zip(a, b)), this is over x10 slower than @BiRico's approach for larger arrays.
yeah thats probably a reasonable statement ... what about if you dont need to convert it back into a np.array? (Im too lazy to check)
5

It seems like you want to add a new axis between 0 and 1 so put the None in the middle. This will shift axis 1 be axis 2 and create a new dimension at 1. Like so:

a = array([[1,1,1],[2,2,2],[3,3,3]])
b = array([[10,10,10],[20,20,20],[30,30,30]])
c = concatenate((a[:, None, :], b[:, None, :]), axis=1)

>>> c
array([[[ 1,  1,  1],
    [10, 10, 10]],

   [[ 2,  2,  2],
    [20, 20, 20]],

   [[ 3,  3,  3],
    [30, 30, 30]]])

Comments

2

You're looking for numpy.stack. It's used for joining arrays along a new axis; in contrast to 'numpy.concatenate', which is for joining arrays along an existing axis. With stack, you specify the axis to join along in terms of which axis it would be after the stacking; so you would specify axis 1.

a = array([[1,1,1],[2,2,2],[3,3,3]])
b = array([[10,10,10],[20,20,20],[30,30,30]])
c = stack((a, b), axis=1)

>>> c
array([[[ 1,  1,  1],
    [10, 10, 10]],

   [[ 2,  2,  2],
    [20, 20, 20]],

   [[ 3,  3,  3],
    [30, 30, 30]]])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.