向矩阵(数组)列表中添加新列

1 投票
2 回答
2900 浏览
提问于 2025-04-16 22:01

我在Python中遇到了关于列表/数组/矩阵的问题。

我有一个矩阵的列表(或者如果需要的话也可以是数组),我想在每一个矩阵中添加一列全是1的新列(行数要和原来的矩阵一样)。我该怎么做呢?

我试过几种方法,但都没有成功。

谢谢大家的帮助。

这里有个例子:

>>> 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 个回答

1

2D列数组:

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

2D行数组:

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

这是一个关于二维 NumPy 数组的例子:

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

补充说明:对于矩阵来说也是一样的。如果你有一组矩阵,可以使用一个循环来处理:

>>> 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)))

撰写回答