Numpy转置用法

时间:2013-12-26 11:31:01

标签: python numpy matrix

无法理解为什么numpy不会转置矩阵。

这不起作用:

w=2
h=3
rc= np.array([[0,0,1],[0,h,1],[w,h,1],[w,0,1]])

array([[0, 0, 1],
       [0, 3, 1],
       [2, 3, 1],
       [2, 0, 1]])

rc[0].T

array([0, 0, 1])

但这有效:

v_x= np.array([[0,1,2,3]])
v_x.T
array([[0],
       [1],
       [2],
       [3]])

3 个答案:

答案 0 :(得分:4)

你的rc [0]不是1x3矩阵,而是3个项目的向量:

>>> rc[0].shape
(3,)

如果要转置它,请修复其形状:

>>> np.reshape(rc[0], (1,3)).T
array([[0],
       [0],
       [1]])

答案 1 :(得分:2)

面对这样的问题时,我要问的第一件事就是:形状是什么?

In [14]: rc.shape
Out[14]: (4, 3)

In [15]: rc[0].shape
Out[15]: (3,)

索引已选择一行,并减少了维度数。

但如果我使用列表(或数组)进行索引,则结果为2d

In [16]: rc[[0]].shape
Out[16]: (1, 3)
In [19]: v_x.shape
Out[19]: (1, 4)

还有其他方法可以获得这种形状,甚至是目标(3,1)

rc[0].reshape(1,-1) # -1 stands in for the known 3
rc[0][np.newaxis,:] # useful when constructing outer products

rc[0].reshape(-1,1) # transposed
rc[0][:,np.newaxis]

np.matrixnp.array的子类,总是2d(即使用标量索引后)

rcm = np.matrix(rc)
rcm[0] # (1,3)
rcm[0].T # (3,1)
如果从MATLAB进入np.matrix

numpy可以简化过渡,尤其是旧版本,其中所有内容都是2d矩阵。对于其他人而言,最好熟悉ndarray,并且只有在添加某些功能时才使用matrix

答案 2 :(得分:1)

转置实际上有效,但不如您预期的那样,see docs

  

默认情况下,反转尺寸

因此,当您的数组为1d时,反向对其形状不执行任何操作:

>>> np.array([0,0,1]).T.shape
(3,)

您可以使用reshape添加更多维度:

>>> np.array([0,0,1]).reshape(-1,1,1).shape
(3, 1, 1)

现在,非平凡的形状可以逆转:

>>> np.array([0,0,1]).reshape(-1,1,1).T.shape
(1, 1, 3)