James Atwood - 1 year ago 288

Python Question

Let's say I have a 1d numpy array

`a=[1,0,3]`

I would like to encode this as a 2d 1-hot array

`b=[[0,1,0,0], [1,0,0,0], [0,0,0,1]]`

Is there a quick way to do this? Quicker than just looping over a to set elements of b, that is.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Your array `a`

defines the columns, you just need to define the rows and then use fancy indexing:

```
>>> a = np.array([1, 0, 3])
>>> b = np.zeros((3, 4))
>>> b[np.arange(3), a] = 1
>>> b
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
>>>
```

This is just for illustration. You may want to choose a more appropriate `dtype`

for `b`

such as `np.bool`

.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**