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]]
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()
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.
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.
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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With