python - numpy 数组的 3D 平铺

标签 python arrays numpy

提供一维数组作为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, promote A to d-dimensions manually before calling this function.

获得所需结果的最简单方法是切片 aNone (或等效地,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/

相关文章:

python - Mac 上应该有多少个不同的 macOS 系统默认版本的 Python?

php - 从多维数组中提取值

JavaScript:动态创建数组

javascript - 如何在javascript中创建数组作为属性?

python - 如何在 NumPy 数组中查找连续元素的组

python - numpy,重新排列 : Methods to convert a list of dict's to a np. 重新排列?

python - 检查字符串是否包含 Python 列表中的元素时出错?

python - 如何从二进制字段查找文件 mimetype

python - 如何按日期过滤 numpy.ndarray?

python - DjangoCMS 添加子插件按钮