![](/img/trans.png)
[英]How to append a last column (1d array) to a 2d numpy array in python?
[英]How to append a column to a 2d numpy array in Python 2.7?
我有兩個numpy數組。 一個是2d矩陣,有3列4行。 第二個numpy數組是一個包含4個值的1d數組。 有沒有辦法將第二個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])
我希望輸出看起來像這樣
[[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.
任何和所有的幫助表示贊賞。 非常感謝!
你可以使用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]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.