“堆叠"新维度的数组? [英] "stacking" arrays in a new dimension?

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

问题描述

考虑,以供参考:

>>> x, y = np.ones((2, 2, 2)), np.zeros((2, 2, 2))
>>> np.concatenate((x, y, x, y), axis=2)
array([[[ 1.,  1.,  0.,  0.,  1.,  1.,  0.,  0.],
        [ 1.,  1.,  0.,  0.,  1.,  1.,  0.,  0.]],

       [[ 1.,  1.,  0.,  0.,  1.,  1.,  0.,  0.],
        [ 1.,  1.,  0.,  0.,  1.,  1.,  0.,  0.]]])

我们沿最里面的维度堆叠了数组,将其合并-生成的形状为(2, 2, 8).但是,假设我希望这些最里面的元素并排放置(这只会起作用,因为源数组的每个维都是相同的,包括我要堆叠"的维),生成的结果形状为如下?

We have stacked the arrays along the innermost dimension, merging it - the resulting shape is (2, 2, 8). But suppose I wanted those innermost elements to lie side-by-side instead (this would only work because every dimension of the source arrays is the same, including the one I want to 'stack' in), producing a result with shape (2, 2, 4, 2) as follows?

array([[[[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]],

        [[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]]],


       [[[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]],

        [[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]]]])

我最好的方法是首先对每个源数组进行整形,在最后一个数组之前添加一个长度为1的维度:

The best approach I have is to reshape each source array first, to add a 1-length dimension right before the last:

def pad(npa):
    return npa.reshape(npa.shape[:-1] + (1, npa.shape[-1]))

np.concatenate((pad(x), pad(y), pad(x), pad(y)), axis=2) # does what I want
# np.hstack might be better? I always want the second-last dimension, now

但是我觉得我正在重新发明轮子.我是否忽略了一些可以更直接地做到这一点的东西?

But I feel like I am reinventing a wheel. Have I overlooked something that will do this more directly?

推荐答案

您可以执行以下操作:

>>> xx = x[..., None, :]
>>> yy = y[..., None, :]
>>> np.concatenate((xx, yy, xx, yy), axis=2).shape
(2, 2, 4, 2)
>>> np.concatenate((xx, yy, xx, yy), axis=2)
array([[[[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]],

        [[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]]],


       [[[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]],

        [[ 1.,  1.],
         [ 0.,  0.],
         [ 1.,  1.],
         [ 0.,  0.]]]])
>>> 

此示例所做的是更改数组的形状(不复制任何数据).切片None或等效地np.newaxis会添加一个轴:

What this example does is change the shape (no data is copied) of the arrays. Slicing with None or equivalently np.newaxis adds an axis:

>>> xx.shape
(2, 2, 1, 2)
>>> xx
array([[[[ 1.,  1.]],

        [[ 1.,  1.]]],


       [[[ 1.,  1.]],

        [[ 1.,  1.]]]])
>>> 

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

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