将新列添加到矩阵列表(数组)

时间:2011-07-21 21:33:41

标签: python numpy

我在Python上遇到了list / arrays / matrix的问题。

我有一个矩阵列表(如果需要的话,还有数组),我想在它们的每一个中添加一列新的(相同行数)。我怎么能这样做?

我有几件事并没有取得任何成功。

感谢您的帮助。

以下是一个例子:

>>> A=[mat([[1,2,3],[4,5,6],[7,8,9]]),mat([[1,0,0],[0,1,0],[0,0,1]])]
>>> A
[matrix([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]), matrix([[1, 0, 0],
        [0, 1, 0],
        [0, 0, 1]])]

使用你们回答的答案

>>> A = np.hstack((A, np.ones((A.shape[0],1),dtype=A.type)))

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    A = np.hstack((A, np.ones((A.shape[0],1),dtype=A.type)))
AttributeError: 'list' object has no attribute 'shape'`

2 个答案:

答案 0 :(得分:3)

2D NumPy ndarray的示例:

>>> m = np.arange(12).reshape(3,4)
>>> m = np.hstack((m, np.ones((m.shape[0], 1), dtype=m.dtype)))
>>> m
array([[ 0,  1,  2,  3,  1],
       [ 4,  5,  6,  7,  1],
       [ 8,  9, 10, 11,  1]])

编辑:矩阵的工作方式相同。对于矩阵列表,您可以使用for循环:

>>> matrices = [np.matrix(np.random.randn(3,4)) for i in range(10)]
>>> for i, m in enumerate(matrices):
...     matrices[i] = np.hstack((m, np.ones((m.shape[0], 1), dtype=m.dtype)))

答案 1 :(得分:1)

2d列数组:

for matrix in matricies:
    matrix.append([1,] * len(matrix[0]))

2d行数组:

for matrix in matricies:
    for row in matrix:
        row.append(1)