以新维度堆叠数组(numpy) [英] Stacking arrays in new dimension (numpy)

查看:486
本文介绍了以新维度堆叠数组(numpy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个数组

k = np.array([[1,1],[2,2]])
m = np.array([[3,3],[4,4]])
n = np.array([[5,5],[6,6]])

理想情况下,我希望获得形状为(3,2,2)的最终阵列,即

I ideally I would like to achieve a final arrays of a shape (3,2,2), i.e.

array([[[1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4]]

       [[5, 5],
        [6, 6]]])

所以我做了

l = np.stack((k,m), axis=0)

并得到一个数组

array([[[1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4]]])

大小(2,2,2).但是,当我尝试追加/堆叠n数组时,总是会得到错误的尺寸错误.我可以做np.dstack,但那没有给我我想要的东西.任何帮助,将不胜感激.谢谢.

of size (2,2,2). However, when I tried to append/stack the n array, I always got an error of wrong dimension. I could do np.dstack but that's not giving me what I want. Any help with this would be very much appreciated. Thank you.

推荐答案

仅出于完整性考虑,为了解决这个问题,Akavall和f5r5e5d提出的答案都是可行的解决方案.

Just for the sake of completeness and to close this question, the answers suggested by Akavall and f5r5e5d are all working solutions.

# Akavall's solution
np.stack((k, m, n), axis=0)

# f5r5e5d's solution
np.array([k,m,n])

# my approach
In [38]: np.concatenate((k[None, :, :], m[None, :, :], n[None, :, :]))
Out[38]: 
array([[[1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4]],

       [[5, 5],
        [6, 6]]])

这篇关于以新维度堆叠数组(numpy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆