Skip to content

[Python] Convert the value to one-hot type in Numpy

Numpy is an important package for processing data in Python. It is often used for various data analysis tasks.

Today I had a requirement for converting some data of numpy array to one-hot encoding type, so I recorded how to use eye() function built-in numpy to do it.

If you have interested for numpy, maybe you can refer this website: https://docs.scipy.org/doc/numpy/user/quickstart.html


one-hot encoding

Before we starting, I want to introduce about what is one-hot encodng.

Assume we have a following array:

[1, 2, 3]


We convert the array to one-hot encoding type, it will look like:

[[0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 1]]

Index is start from , one-hot encoding is the above type.


Convert Numpy Array to One-Hot Encoding

We back to eye() function.

Also assume we have the following numpy array:

import numpy as np
list = np.array([1, 2, 3])
print(list)



Output:

[1 2 3]



Assume index is start from 0, so we can see that the length of each array in one-hot encdoing array is 4.

Then we just use the following command to convert.

print(np.eye(4)[list])



Output:

[[0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

We done!

Leave a Reply