Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a binary classes column to numpy array

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]]
like image 846
xtiger Avatar asked Dec 31 '16 13:12

xtiger


People also ask

Can you convert a list to a NumPy array?

Lists can be converted to arrays using the built-in functions in the Python numpy library. numpy provides us with two functions to use when converting a list into an array: numpy. array()

How do I turn a column into a DataFrame array?

It is quite easy to transform a pandas dataframe into a numpy array. Simply using the to_numpy() function provided by Pandas will do the trick. This will return us a numpy 2D array of the same size as our dataframe (df), but with the column names discarded.

How do you convert a 1d array to a 2D array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.

How do I create a NumPy array from a DataFrame?

To convert Pandas DataFrame to Numpy Array, use the function DataFrame. to_numpy() . to_numpy() is applied on this DataFrame and the method returns object of type Numpy ndarray. Usually the returned ndarray is 2-dimensional.


1 Answers

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]]
like image 113
Divakar Avatar answered Sep 29 '22 10:09

Divakar