首页 > 解决方案 > 在 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]]]

我的功能应该是什么?

标签: pythonnumpy

解决方案


你可以使用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))

推荐阅读