2014-02-25 72 views
0

我知道有很多關於numpy列的問題和答案,但我仍然陷入困境。在numpy中添加列 - 仍然困惑

np.append沒有工作對我來說,它說沒有模塊

我它有一個從主boston.data分開存放中間值波士頓數據集的工作(形狀( 506,13)as boston.target(shape is(506,1))。我想讓它成爲boston.target特性(又名列)添加到boston.data中,使其形狀爲(506, 14),與boston.data [13]爲boston.target數據。

我嘗試,基於關閉的其他建議,我已經看到了一直

np.append(boston.data,boston.target ,軸= 0) 打印boston.data.shape

給我一個錯誤:ValueError異常:所有的輸入陣列必須具有相同的維數

做只是np.append(boston.data,boston.target的) 它不給我任何....它返回相同的boston.data,或者至少據我所知。

我做錯了什麼?

編輯:完整的代碼,如果任何人有IPython的打開,低於

import numpy as np 
import matplotlib 
import matplotlib.pyplot as plt 
from sklearn.datasets import load_boston 
boston = load_boston() 

print boston.data.shape 
print boston.target.shape 
copyarr = np.append(boston.data, boston.target, axis=1) #changed still runs error 
print copyarr.shape 

at --> copyarr = np.append(boston.data, boston.target, axis=1) 
ValueError: all the input arrays must have the same number of dimensions 

回答

0

首先,你應該設置軸= 1,不是0 您正在嘗試添加一列,而不是行。這就是numpy爲數組提供不同維數的錯誤原因。

import numpy as np 
A = np.append(boston.data, boston.target.reshape(-1, 1), axis=1) 

添加列的另一種方法是使用hstack。

import numpy as np 
A = np.hstack((boston.data, boston.target.reshape(-1, 1))) 

問題的原因是boston.target已經形成(506,)。它是一維數組,而boston.data具有形狀(506,13),這是一個2D數組。您需要使用boston.target.reshape(-1, 1)顯式重塑boston.target以具有形狀(506,1),其中-1意味着推斷行數,以便將數據重新整形爲1列。

另請注意,在這兩種情況下,都會創建一個數組的副本,即數組boston.data未就地修改。這意味着追加列的結果應該存儲在另一個變量中,如上所示。

+0

所以我將不得不分配一個新的數組來保存副本?恩。 copyarray = np.hstack((boston.data,boston.target))無論如何,這仍然給我一個錯誤,這次:ValueError:所有輸入數組必須具有相同的維數 – user2635779

+0

我編輯了我的答案。你的數組'boston.target'沒有形狀(506,1)。它有形狀(506,),這是不同的。 – lightalchemist

+0

謝謝 - 這是有道理的。 – user2635779