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.

2
  • you can use OneHotEncoder Commented Oct 18, 2017 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. Commented Oct 18, 2017 at 19:45

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.