Say I've got
Y = np.array([2, 0, 1, 1])
From this I want to obtain a matrix X with shape (len(Y), 3)
. In this particular case, the first row of X should have a one on the second index and zero otherwhise. The second row of X should have a one on the 0 index and zero otherwise. To be explicit:
X = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 0]])
How do I produce this matrix? I started with
X = np.zeros((Y.shape[0], 3))
but then couldn't figure out how to populate/fill in the ones from the list of indices
As always, thanks for your time!
Creating a Two-dimensional Array If you only use the arange function, it will output a one-dimensional array. To make it a two-dimensional array, chain its output with the reshape function. First, 20 integers will be created and then it will convert the array into a two-dimensional array with 4 rows and 5 columns.
convert a 1-dimensional array into a 2-dimensional array by adding new axis. a=np. array([10,20,30,40,50,60]) b=a[:,np. newaxis]--it will convert it to two dimension.
If I have to create a 2D array of 1s or 0s, I can use numpy. ones() or numpy. zeros() respectively.
2D array are also called as Matrices which can be represented as collection of rows and columns. In this article, we have explored 2D array in Numpy in Python. NumPy is a library in python adding support for large multidimensional arrays and matrices along with high level mathematical functions to operate these arrays.
Maybe:
>>> Y = np.array([2, 0, 1, 1])
>>> X = np.zeros((len(Y), 3))
>>> X[np.arange(len(Y)), Y] = 1
>>> X
array([[ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 1., 0.],
[ 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