假设我有一个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])
,但它没有用。
答案 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>