Question: How to convert a binary classes column to numpy array

Question

How to convert a binary classes column to numpy array

Answers 1
Added at 2016-12-31 14:12
Tags
Question

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]]
Answers
nr: #1 dodano: 2016-12-31 14:12

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]]
Source Show
◀ Wstecz