通过沿第一个轴进行复制/重复操作从2D数组创建3D数组 [英] Create 3D array from a 2D array by replicating/repeating along the first axis

查看:79
本文介绍了通过沿第一个轴进行复制/重复操作从2D数组创建3D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个n × m数组,即:

Suppose I have a n × m array, i.e.:

array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])

然后我要生成一个3D数组k × n × m,其中新轴上的所有数组都相等,即:相同的数组,但现在为3 × 3 × 3.

And I what to generate a 3D array k × n × m, where all the arrays in the new axis are equal, i.e.: the same array but now 3 × 3 × 3.

array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]],

      [[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]],

      [[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]]])

我怎么得到它?

推荐答案

Introduce a new axis at the start with None/np.newaxis and replicate along it with np.repeat. This should work for extending any n dim array to n+1 dim array. The implementation would be -

np.repeat(arr[None,...],k,axis=0)

样品运行-

In [143]: arr
Out[143]: 
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])

In [144]: np.repeat(arr[None,...],3,axis=0)
Out[144]: 
array([[[ 1.,  2.,  3.],
        [ 4.,  5.,  6.],
        [ 7.,  8.,  9.]],

       [[ 1.,  2.,  3.],
        [ 4.,  5.,  6.],
        [ 7.,  8.,  9.]],

       [[ 1.,  2.,  3.],
        [ 4.,  5.,  6.],
        [ 7.,  8.,  9.]]])

View-output提高内存效率

View-output for memory-efficiency

我们还可以生成3D视图,并使用 here .因此,只需-

We can also generate a 3D view and achieve virtually free runtime with np.broadcast_to. More info - here. Hence, simply do -

np.broadcast_to(arr,(3,)+arr.shape) # repeat 3 times

这篇关于通过沿第一个轴进行复制/重复操作从2D数组创建3D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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