python - Numpy 中的平铺

标签 python numpy

我有一个包含数据 [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/

相关文章:

python - pandas 数据帧中 .iloc() 的计算复杂度是多少?

Python csv writer 截断数字格式

python - 此 numpy 数组索引的较短版本

python - Pandas 在回溯窗口中找到每个用户的第一个订单的最小日期

python - 如何在事件循环中将协程打包为普通函数?

python - python中根据key值组合字典

python - 在 cython 中修剪一个 numpy 数组

python - 在两组之后将系列转换为数据框

python - 如何将异构数据 (np.genfromtxt) 作为二维数组加载?

python - Python 中正则表达式之后/之前的所有内容