我有一个包含数据 [3, 5]
的 NumPy 数组,我想创建一个接受该数组的函数,并返回以下 (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))
关于python - Numpy 中的平铺,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63020531/