2017-06-20 67 views
0

我有兩個numpy數組。一個是具有3列和4行的2d矩陣。第二個numpy數組是具有4個值的1d數組。有沒有辦法將第二個numpy數組作爲列附加到Python 2.7中的第一個numpy數組?如何在Python 2.7中將列添加到2d 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. 

任何和所有的幫助表示讚賞。非常感謝!

+0

正確的維數:'np.concatenate((arr2d,column_to_add [:,無]),軸= 1)'。 '[:,None]'把1d數組變成2d列數組。 – hpaulj

回答

1

可以使用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]]) 
相關問題