简体   繁体   English

结合numpy多维数组

[英]Combining numpy multi-dimensional arrays

Im 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! 真正的问题是我的阵列a和b比3个坐标长得多!

The best I achieved using concatenate is: 我使用concatenate实现的最好的是:

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... 哪个仍然不起作用......

ummm zip(a,b) ? 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]))]

It seems like you want to add a new axis between 0 and 1 so put the None in the middle. 看起来你想在0和1之间添加一个新轴,所以把None放在中间。 This will shift axis 1 be axis 2 and create a new dimension at 1. Like so: 这将使轴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]]])

You're looking for numpy.stack . 你正在寻找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. 与'numpy.concatenate'形成对比,后者用于沿现有轴连接数组。 With stack , you specify the axis to join along in terms of which axis it would be after the stacking; 随着stack ,您所指定的轴在其中轴这将是叠层条款加入一起; so you would specify axis 1. 所以你要指定轴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]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM