8

I have an array like this as the label column (2 labels : 0 and 1) , for example:

[0,1,0,1,1]

Supposed that I want to convert this array to a numpy matrix with the shape (5,2) (5 elements, 2 labels) . How can I do that in a trivial way by using any util library?

The outcome I want is like this :

[[0,1][1,0],[0,1],[1,0],[1,0]]
2
  • You want to add the other label (0 to 1, and vice versa)?
    – ppasler
    Dec 31, 2016 at 13:40
  • I want to ask if there is any trivial way to do this, because creating a new 2 dimensions array, go through each element, put 1 if existed 0, put 0 if existed 1 is a little bit complicated
    – xtiger
    Dec 31, 2016 at 13:41

1 Answer 1

8

You could use NumPy broadcasting -

(a[:,None] != np.arange(2)).astype(int)

Sample run -

In [7]: a = np.array([0,1,0,1,1])

In [8]: (a[:,None] != np.arange(2)).astype(int)
Out[8]: 
array([[0, 1],
       [1, 0],
       [0, 1],
       [1, 0],
       [1, 0]])

# Convert to list if needed
In [14]: (a[:,None] != np.arange(2)).astype(int).tolist()
Out[14]: [[0, 1], [1, 0], [0, 1], [1, 0], [1, 0]]
1
  • thanks , this is what I want , took me some hours to search for this :)
    – xtiger
    Dec 31, 2016 at 13:45

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.