如何将元素附加到矩阵中的每个向量 - Python

cal*_*011 1 python numpy matrix

我有一个 500x2 矩阵,已使用numpy.random.rand.

输出看起来像这样(但显然是更大的版本):

 [ -3.28460744e+00  -4.29156493e-02]
 [ -1.90772015e-01  -9.17618367e-01]
 [ -2.41166994e+00  -3.76661496e+00]
 [ -2.43169366e+00  -6.31493375e-01]
 [ -1.48902305e+00  -9.78215901e-01]
 [ -3.11016192e+00  -1.87178962e+00]
 [ -3.72070031e+00  -1.66956850e+00]
Run Code Online (Sandbox Code Playgroud)

我想附加1到每行的末尾,以便每行看起来像这样:

[ -3.72070031e+00  -1.66956850e+00  1]
Run Code Online (Sandbox Code Playgroud)

这可能吗?我一直在尝试使用numpy.append()但努力弄清楚应该使用什么。

任何帮助将非常感激!

wwi*_*wii 5

a = np.ones((4,2)) * 2
>>> a
array([[ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.]])
Run Code Online (Sandbox Code Playgroud)

Numpy.concatenate 文档The arrays must have the same shape, except in the dimension corresponding to axis...along which the arrays will be joined.

>>> a.shape
(4, 2)
Run Code Online (Sandbox Code Playgroud)

您想要沿第二个轴连接,因此创建一个形状为 (4,1) 的数组 - 使用 from 的值a.shape来执行此操作。

b = np.ones((a.shape[0], 1))

>>> b.shape
(4, 1)
>>> b
array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])
Run Code Online (Sandbox Code Playgroud)

现在您可以连接

z = np.concatenate((a,b), axis = 1)

>>> z
array([[ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.]])
Run Code Online (Sandbox Code Playgroud)

或者使用hstack

>>> np.hstack((a,b))
array([[ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.]])
Run Code Online (Sandbox Code Playgroud)