提供一维数组作为a
:
a=np.arange(8)
我希望它以 3D 方案复制,以便具有这样的形状 (n1, len(a), n3)
。
有什么有效的方法可以通过 np.tile
获得它吗?这看起来微不足道,但尝试:
np.shape( np.tile(a, (n1,1,n3)) )
或
np.shape( np.tile( np.tile(a, (n1,1)), (1,1,n2) ) )
我从来没有获得我需要的结果形状 (n1, 1, len(a)*n3)
或 (1, n1, len(a)*n3)
。
也许是我不明白 tile
是如何工作的......
最佳答案
发生的事情是a
在应用平铺之前正在制作一个 1x1x8 数组。你需要制作 a
一个 1x8x1 数组,然后调用 tile
.
作为the documentation for tile
备注:
If
A.ndim < d
,A
is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promoteA
to d-dimensions manually before calling this function.
获得所需结果的最简单方法是切片 a
与 None
(或等效地,np.newaxis
)使其成为正确的形状。
举个简单的例子:
import numpy as np
a = np.arange(8)
result = np.tile(a[None, :, None], (4, 1, 5))
print result.shape
关于python - numpy 数组的 3D 平铺,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166471/