如何在Python 2.7中将列添加到2D numpy数组?

4
我有两个numpy数组。一个是拥有3列4行的二维矩阵。第二个numpy数组是一个包含4个值的一维数组。在Python 2.7中,有没有一种方法将第二个numpy数组追加为第一个numpy数组的一列? 例如,如果这是我的两个numpy数组:
arr2d = np.matrix(
[[1, 2, 3],
[4, 5, 6], 
[7, 8, 9], 
[10, 11, 12]])

column_to_add = np.array([10, 40, 70, 100])

我希望输出内容如下所示。
    [[1, 2, 3, 10],
    [4, 5, 6, 40], 
    [7, 8, 9, 70], 
    [10, 11, 12, 100]]

我尝试使用

标签


output = np.hstack((arr2d, column_to_add))

但是我收到了一个错误提示,内容如下:
ValueError: all the input arrays must have the same number of dimensions. 

非常感谢您的帮助。任何帮助都将不胜感激。谢谢!


请更正维度数量:np.concatenate((arr2d, column_to_add[:,None]), axis=1)[:,None] 将一维数组转换为二维列数组。 - hpaulj
1个回答

10

您可以使用numpy.column_stack

import numpy as np

arr2d = np.matrix(
[[1, 2, 3],
[4, 5, 6], 
[7, 8, 9], 
[10, 11, 12]])

column_to_add = np.array([10, 40, 70, 100])

output = np.column_stack((arr2d, column_to_add))

输出:

matrix([[  1,   2,   3,  10],
        [  4,   5,   6,  40],
        [  7,   8,   9,  70],
        [ 10,  11,  12, 100]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接