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...

4

3 回答 3

6

zip(a,b)

是不是你想要的??

>>> 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]))]
于 2013-11-13T16:33:07.413 回答
5

似乎您想在 0 和 1 之间添加一个新轴,所以将 None 放在中间。这会将轴 1 移动到轴 2 并在 1 处创建一个新维度。像这样:

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]]])
于 2013-11-13T16:42:50.267 回答
2

你正在寻找numpy.stack. 它用于沿新轴连接数组;与 'numpy.concatenate' 不同,后者用于沿现有轴连接数组。使用,您可以根据堆叠stack的轴指定要连接的轴;所以你会指定轴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]]])
于 2016-02-09T04:08:17.213 回答