python - 在 Numpy 中平铺
问题描述
我有一个带有 data 的 NumPy 数组[3, 5]
,我想创建一个接受这个数组的函数,并返回以下 (2 x 3 x 2) NumPy 数组:
[[[3, 3],
[3, 3],
[3, 3]],
[[5, 5],
[5, 5],
[5, 5]]]
但是,我无法使用 Numpy 的repeat()
或tile()
函数来实现这一点。
例如:
x = np.array([3, 5])
y = np.repeat(x, [2, 3, 2])
给出以下错误:
ValueError: a.shape[axis] != len(repeats)
和:
x = np.array([3, 5])
y = np.tile(x, [2, 3, 2])
创建一个 (2 x 3 x 4) 数组:
[[[3, 5, 3, 5],
[3, 5, 3, 5],
[3, 5, 3, 5]],
[[3, 5, 3, 5],
[3, 5, 3, 5],
[3, 5, 3, 5]]]
我的功能应该是什么?
解决方案
你可以使用np. tile
,你只是错过了除以重复轴上的元素数量,在你的情况下它是1D
x = np.array([3, 5])
y = np.tile(x, [2, 3, 2 // x.shape[0]])
def get_nd(a, shape):
shape = np.array(shape)
a_shape = np.ones_like(shape)
a_shape[-a.ndim:] = a.shape
shape = (shape * 1/a_shape).astype('int')
return np.tile(a, shape)
get_nd(x, (2, 3, 2))
更新
转置所需的形状,如果您的目标是(2, 3, 6)
,则要求(6, 3, 2)
然后转置结果矩阵
get_nd(x, (2, 3, 6)).T
或者改用下面的函数
def get_nd_rep(a, shape):
shape = np.array(shape)
x_shape = np.ones_like(shape)
x_shape[-a.ndim:] = a.shape
shape = (shape * 1/x_shape).astype('int')
return np.tile(a, shape).T
get_nd_rep(x, (2, 3, 2))
推荐阅读
- perl - perl (5.30.0) 在 MacOS 10.14.6 上安装失败
- java - Java 使用 SAX 解析读取 XML
- java - 数据正在保存到 firebase 数据库,但文件名不正确
- python - 在子图中的第三行添加第二个散点
- reactjs - Jest - 在单元测试时处理基类函数
- android-studio - 模拟器在快照下创建了一个 ram.img.dirty 而不是 ram.img
- python - 不能在 python + pytest 上执行monkeypatch 函数
- c++ - 与不是主线程的 GUI 线程通信
- r - 加速或替换for循环:组重塑和行绑定
- c++ - Opencv cascade.detectMultiScale 没有检测到眼睛