简体   繁体   English

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

[英]How to append a column to a 2d numpy array in Python 2.7?

I have two numpy arrays. 我有两个numpy数组。 One is a 2d matrix that has 3 columns and 4 rows. 一个是2d矩阵,有3列4行。 The second numpy array is a 1d array with 4 values. 第二个numpy数组是一个包含4个值的1d数组。 Is there a way to append the second numpy array as a column to the first numpy array in Python 2.7? 有没有办法将第二个numpy数组作为列附加到Python 2.7中的第一个numpy数组?

For example if these were my two numpy arrays: 例如,如果这些是我的两个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])

I'd like the output to look like this 我希望输出看起来像这样

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

I tried using 我试过用

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

but I got an error that says: 但我得到一个错误,上面写着:

ValueError: all the input arrays must have the same number of dimensions. 

Any and all help is appreciated. 任何和所有的帮助表示赞赏。 Thank you so much! 非常感谢!

You can use numpy.column_stack : 你可以使用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))

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM