2017-10-18 136 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>