【问题标题】:Reshape and concatenate within a numpy array在 numpy 数组中重塑和连接
【发布时间】:2020-02-08 22:08:51
【问题描述】:

我想知道是否存在转换这样一个矩阵的简单方法:

[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]

进入

[[1 ,2 ,5 ,6 ],
 [3 ,4 ,7 ,8 ],
 [9 ,10,13,14],
 [11,12,15,16]]

这相当于将每个初始列表reshape成2x2矩阵,然后将它们连接起来; 例如 np.array([1,2,3,4]).reshape((2,2)) 给出 [[1,2],[3,4]]

np.array([5, 6, 7, 8]).reshape((2,2)) 给出 [[5,6],[7,8]]

所以

np.concatenate((np.array([1,2,3,4]).reshape((2,2)), np.array([5, 6, 7, 8]).reshape((2,2))), axis=1)

会给

array([[1 ,2 ,5 ,6 ],
       [3 ,4 ,7 ,8 ]])

等等……

这确实是一个虚拟的例子,因为我需要处理更多(和更大)的矩阵,我必须找到一个更直接的方法。

【问题讨论】:

  • 如果我理解正确,你想“删除”第二个维度?

标签: python arrays numpy


【解决方案1】:

我们可以将reshapeswapaxesconcatenate 沿第一轴使用:

np.concatenate(a.reshape(a.shape[0], a.shape[1], 2, -1)
                 .swapaxes(1,2)
                 .reshape(a.shape))

array([[ 1,  2,  5,  6],
       [ 3,  4,  7,  8],
       [ 9, 10, 13, 14],
       [11, 12, 15, 16]])

【讨论】:

  • 哇!这很让人佩服!非常感谢!现在我只需要学习和理解这个我不知道的交换轴方法:)
  • 最后我无法将它应用于我的问题...我有 Q.shape = (10,10,784),并且我想以与我的示例相同的方式找到 (280,280 ) 异形矩阵;我最终使用了data = np.array([]) for l in Q: ligne = np.array([]) for s in l: if ligne.shape == (0,) : ligne = s.reshape((28,28)) else: ligne = np.concatenate((ligne, s.reshape((28,28))), axis=1) if data.shape == (0,) : data = ligne else: data = np.concatenate((data, ligne), axis=0)
  • np.concatenate(Q.reshape(a, b, c, -1).swapaxes(d,e).reshape(Q.shape)) 的 a,b,c,d,e 是什么?
  • 糟糕的是我硬编码了前两个轴,现在试试@Netchaiev
  • 仍然无法正常工作(我最后得到一个 100x784 矩阵...),因为在我感兴趣的矩阵 Q 中,Q.shape[0] 和 Q.shape[1] 将为 10 并且,在某些时候,我想必须将 784 个长列表变成 28x28 矩阵...
猜你喜欢
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-10
  • 2020-07-11
  • 1970-01-01
  • 2011-10-01
  • 2018-04-13
相关资源
最近更新 更多