用numpy数组替换1d numpy数组中的元素

时间:2017-10-18 19:30:31

标签: python arrays numpy

假设我有一个numpy数组x = np.array([0, 1, 2]),python中是否有内置函数,以便将元素转换为相应的数组?

e.g。 我想将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]),但它没有用。

1 个答案:

答案 0 :(得分: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>