Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct two dimensional numpy array from indices and values of a one dimensional array

Tags:

python

numpy

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!

like image 248
cd98 Avatar asked Sep 23 '13 20:09

cd98


People also ask

How do you create a 2-dimensional NumPy array?

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.

How do you make a NumPy array 1-dimensional to 2-dimensional?

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.

Which function creates a 2D array with all values 1?

If I have to create a 2D array of 1s or 0s, I can use numpy. ones() or numpy. zeros() respectively.

What is 2D NumPy array in Python?

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.


1 Answers

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.]])
like image 61
DSM Avatar answered Oct 27 '22 00:10

DSM