0

Say I have a numpy array x = np.array([0, 1, 2]), is there a built-in function in python so that I convert element to corresponding array?

e.g. I want to convert 0 in x to [1, 0, 0], 1 to [0, 1, 0], 2 to [0, 0, 1], and the expected output is np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).

I tried x[x == 0] = np.array([1, 0, 0]) but it doesn't work.

user21
  • 329
  • 2
  • 15
  • you can use [OneHotEncoder](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html) – MaxU - stand with Ukraine Oct 18 '17 at 19:35
  • Oh yeah, it is a duplicate. I find there's a nice answer in a link of the answer in that post, though the wording of the question is really different so I didn't find it ....Seems like I can't delete my question so I flag it. – user21 Oct 18 '17 at 19:45

1 Answers1

0

Demo:

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>
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419