通过沿第一个轴进行复制/重复操作从2D数组创建3D数组 [英] Create 3D array from a 2D array by replicating/repeating along the first axis
问题描述
假设我有一个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.]]])
我怎么得到它?
推荐答案
以 np.repeat
.这对于将任何n
暗淡数组扩展为n+1
暗淡数组应该起作用.实现将是-
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屋!