繁体   English   中英

将向量作为新列添加到矩阵

[英]Adding a vector as a new column to a matrix

我有一个包含6行5列的矩阵,以及一个长度为6的1d向量,我想将其作为新的第6列添加到我的矩阵中,以得到6x6矩阵。

一维向量

[0.77777777777777779, 0.061224489795918366, 0.86864406779661019, 0.66666666666666663, 0.96470588235294119, 83.333333333333343]

矩阵

[[  42.            0.            6.            0.            6.        ]
 [   0.            3.            8.            0.           38.        ]
 [   6.            0.          205.            0.           25.        ]
 [   0.            0.            2.            4.            0.        ]
 [   1.            0.            8.            0.          246.        ]
 [   0.85714286    1.            0.89519651    1.            0.78095238]]

我已经尝试过np.hstack但这不适用于这项工作。

np.hstack([matrix, vector])不起作用的原因是因为形状彼此不匹配:

>>> vector.shape
(6,)
>>> matrix.shape
(6, 5)

但是,如果你做vector用的向量vector[:, np.newaxis]然后np.hstack可以处理形状:

>>> matrix = np.arange(30).reshape(6,5)
>>> vector = -np.ones(6)
>>> matrix
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29]])
>>> vector
array([-1., -1., -1., -1., -1., -1.])
>>> vector[:, np.newaxis]
array([[-1.],
       [-1.],
       [-1.],
       [-1.],
       [-1.],
       [-1.]])
>>> vector[:, np.newaxis].shape
(6, 1)
>>> np.hstack([matrix, vector])
Rückverfolgung (innerste zuletzt):
  Python-Shell, prompt 23, line 1
  File "C:\Python34\Lib\site-packages\numpy\core\shape_base.py", line 293, in hstack
    return _nx.concatenate(arrs, 1)
builtins.ValueError: all the input arrays must have same number of dimensions
>>> np.hstack([matrix, vector[:, np.newaxis]])
array([[  0.,   1.,   2.,   3.,   4.,  -1.],
       [  5.,   6.,   7.,   8.,   9.,  -1.],
       [ 10.,  11.,  12.,  13.,  14.,  -1.],
       [ 15.,  16.,  17.,  18.,  19.,  -1.],
       [ 20.,  21.,  22.,  23.,  24.,  -1.],
       [ 25.,  26.,  27.,  28.,  29.,  -1.]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM