Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list into Numpy ndarray [duplicate]

Tags:

I want to convert this list

li = [3, 2 , 1 , 4]

to the following NumPy ndarray

[[3], [2], [1], [4]]

I tried with np.asarray() but it is not converting it into an ndarray. Is there any way to mention the axis?

like image 786
syv Avatar asked Apr 12 '18 03:04

syv


1 Answers

You can use numpy.expand_dims to create an array with an extra axis,

>>> np.expand_dims(li, -1)
array([[3],
       [2],
       [1],
       [4]])

or if you prefer, add the axis after array creation.

np.array(li)[..., np.newaxis]
like image 127
miradulo Avatar answered Sep 28 '22 05:09

miradulo