How to convert a column of binary classes to a numpy array

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

[0,1,0,1,1] 

Suppose I want to convert this array to a numpy matrix with the form (5,2) (5 elements, 2 labels). How can I do this trivially using any utility library?

The result I want is as follows:

 [[0,1][1,0],[0,1],[1,0],[1,0]] 
+5
source share
1 answer

You can use NumPy broadcasting -

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

Run Example -

 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]] 
+7
source

Source: https://habr.com/ru/post/1262123/


All Articles