如何在 Python 2.7 中将一列附加到 2d numpy 数组?

CSL*_*ner 4 python arrays numpy python-2.7

我有两个 numpy 数组。一个是具有 3 列和 4 行的 2d 矩阵。第二个 numpy 数组是具有 4 个值的一维数组。有没有办法将第二个 numpy 数组作为列附加到 Python 2.7 中的第一个 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])
Run Code Online (Sandbox Code Playgroud)

我希望输出看起来像这样

    [[1, 2, 3, 10],
    [4, 5, 6, 40], 
    [7, 8, 9, 70], 
    [10, 11, 12, 100]]
Run Code Online (Sandbox Code Playgroud)

我尝试使用

output = np.hstack((arr2d, column_to_add))
Run Code Online (Sandbox Code Playgroud)

但我收到一条错误消息:

ValueError: all the input arrays must have the same number of dimensions. 
Run Code Online (Sandbox Code Playgroud)

任何和所有的帮助表示赞赏。非常感谢!

FJS*_*lla 9

您可以使用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))
Run Code Online (Sandbox Code Playgroud)

输出:

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