【问题标题】:How to append element to each vector in a matrix - Python [duplicate]如何将元素附加到矩阵中的每个向量 - Python [重复]
【发布时间】:2016-10-31 00:43:47
【问题描述】:

我有一个使用numpy.random.rand 填充的 500x2 矩阵。

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

 [ -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]

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

[ -3.72070031e+00  -1.66956850e+00  1]

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

任何帮助将不胜感激!

【问题讨论】:

  • np.append(arr, np.ones((500, 1)), axis=-1)
  • 谢谢@Eric!但这不是返回一个填充 1 的数组吗?
  • 你为什么希望它返回一个满是 1 的数组?
  • @Eric 哦,对不起,我根本没想到!效果非常好 - 谢谢!
  • 学习和练习使用np.concatenate。这是所有堆栈和附加功能的基础。

标签: python numpy matrix


【解决方案1】:
a = np.ones((4,2)) * 2
>>> a
array([[ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.]])

Numpy.concatenate documentation: 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)

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

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

>>> b.shape
(4, 1)
>>> b
array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

现在你可以连接

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

>>> z
array([[ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.]])

或使用hstack

>>> np.hstack((a,b))
array([[ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.]])

【讨论】:

    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    相关资源
    最近更新 更多