2017-10-18 121 views
0

假設我有一個numpy數組x = np.array([0, 1, 2]),python中是否有內置函數,以便將元素轉換爲相應的數組?用numpy數組替換1d numpy數組中的元素

例如 我想將x中的0轉換爲[1,0,0],1轉換爲[0,1,0],2轉換爲[0,0,1],期望的輸出爲np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])。我試過x[x == 0] = np.array([1, 0, 0])但它不起作用。

+0

您可以使用[OneHotEncoder(http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html) – MaxU

+0

噢,這是一個重複。我發現這篇文章的答案中有一個很好的答案,儘管問題的措辭是非常不同的,所以我沒有找到它....似乎我不能刪除我的問題,所以我標記它。 – user21

回答

0

演示:

In [38]: from sklearn.preprocessing import OneHotEncoder 

In [39]: ohe = OneHotEncoder() 

# modern versions of SKLearn methods don't like 1D arrays 
# they expect 2D arrays, so let's make it happy ;-)  
In [40]: res = ohe.fit_transform(x[:, None]) 

In [41]: res.A 
Out[41]: 
array([[ 1., 0., 0.], 
     [ 0., 1., 0.], 
     [ 0., 0., 1.]]) 

In [42]: res 
Out[42]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>' 
     with 3 stored elements in Compressed Sparse Row format>