2017-10-16 182 views
0

我有這樣的數組:
enter image description here的Python:基於另一個陣列多個列的新數組

我需要創建一個新的數組是這樣的:
enter image description here

我想我需要使用有條件的,但我不知道如何創建一個基於5列數組值的7列的數組。

如果有人能幫助我,我感謝!

+2

你從未解釋過該行的最後一個數字是如何影響0/1這被寫入最後? – AK47

+0

[np.hstack()](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.hstack.html) – sascha

回答

1

我打算假設您想將最後一列轉換爲一個熱解析結果,然後將其轉換爲原始數組。您可以初始化一個零數組,然後將適當的索引設置爲1。最後將OHE陣列連接到原來的。


MCVE:使用np.eye招@COLDSPEED的

print(arr) 
array([[ -9.95, 15.27, 9.08, 1. ], 
     [ -6.81, 11.87, 8.38, 2. ], 
     [ -3.02, 11.08, -8.5 , 1. ], 
     [ -5.73, -2.29, -2.09, 2. ], 
     [ -7.01, -0.9 , 12.91, 2. ], 
     [-11.64, -10.3 , 2.09, 2. ], 
     [ 17.85, 13.7 , 2.14, 0. ], 
     [ 6.34, -9.49, -8.05, 2. ], 
     [ 18.62, -9.43, -1.02, 1. ], 
     [ -2.15, -23.65, -13.03, 1. ]]) 

c = arr[:, -1].astype(int)  
ohe = np.zeros((c.shape[0], c.max() + 1)) 
ohe[np.arange(c.shape[0]), c] = 1 

arr = np.hstack((arr[:, :-1], ohe)) 

print(arr) 
array([[ -9.95, 15.27, 9.08, 0. , 1. , 0. ], 
     [ -6.81, 11.87, 8.38, 0. , 0. , 1. ], 
     [ -3.02, 11.08, -8.5 , 0. , 1. , 0. ], 
     [ -5.73, -2.29, -2.09, 0. , 0. , 1. ], 
     [ -7.01, -0.9 , 12.91, 0. , 0. , 1. ], 
     [-11.64, -10.3 , 2.09, 0. , 0. , 1. ], 
     [ 17.85, 13.7 , 2.14, 1. , 0. , 0. ], 
     [ 6.34, -9.49, -8.05, 0. , 0. , 1. ], 
     [ 18.62, -9.43, -1.02, 0. , 1. , 0. ], 
     [ -2.15, -23.65, -13.03, 0. , 1. , 0. ]]) 
+1

完美!很好解釋!謝謝! :) – rponciano

1

一個行版本:

np.hstack([arr[:,:-1], np.eye(arr[:,-1].astype(int).max() + 1)[arr[:,-1].astype(int)]]) 
相關問題