Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I am trying to convert a numpy array
np.array([1,3,2])
to
np.array([[1,0,0],[0,0,1],[0,1,0]])
Any idea of how to do this efficiently? Thanks!
Create an bool array, and then fill it:
import numpy as np a = np.array([1, 2, 3, 0, 3, 2, 1]) b = np.zeros((len(a), a.max() + 1), bool) b[np.arange(len(a)), a] = 1
Add a comment
It is also possible to just select the right values from np.eye or the identity matrix:
np.eye
a = np.array([1,3,2]) b = np.eye(max(a))[a-1]
This would probably be the most straight forward.
You can compare to [1, 2, 3] like so:
[1, 2, 3]
>>> a = np.array([1,3,2]) >>> np.equal.outer(a, np.arange(1, 4)).view(np.int8) array([[1, 0, 0], [0, 0, 1], [0, 1, 0]], dtype=int8)
or equivalent but slightly faster
>>> (a[:, None] == np.arange(1, 4)).view(np.int8)
Try pandas's get dummy method.
import pandas as pd import numpy as np arr = np.array([1 ,3, 2]) df = pd.get_dummies(arr)
if what you need is numpy array object, do:
arr2 = df.values
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.