Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting list into individual separate list

Tags:

python

numpy

I have a numpy.ndarray which is like this:

X = array([1., 1., 1., 1., 1., 1., 1., 2., 1., 1.])

I tried to convert into lists by doing this:

samples = X.reshape(len(X)).tolist()

which gave output like this

[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0]

tried to convert the above into separate lists. did this

new_list = [samples[i] for i in range(10)]

which gave an output like this again:

[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0]

im trying to get an output like this:

[1.0]
[1.0]
[1.0]
[1.0]
[1.0]
[1.0]
[1.0]
[2.0]
[1.0]
[1.0]

can anyone help me out with this?

like image 734
Sheetal Patel Avatar asked Jan 27 '23 07:01

Sheetal Patel


2 Answers

Using list comprehension, more details

Replace your code:

new_list = [samples[i] for i in range(10)]

To

new_list = [[samples[i]] for i in range(10)]

O/P:

[[1.0], [1.0], [1.0], [1.0], [1.0], [1.0], [1.0], [2.0], [1.0], [1.0]]
like image 74
bharatk Avatar answered Jan 31 '23 00:01

bharatk


Add an aditional axis to your numpy array using either None or np.newaxis, and then use ndarray.tolist, which will directly give you a nested list:

X[:,None].tolist()
# [[1.0], [1.0], [1.0], [1.0], [1.0], [1.0], [1.0], [2.0], [1.0], [1.0]]

Your approach with np.reshape does not work as you're not adding any axis, you'd need:

X.reshape(len(X), 1).tolist() 
like image 23
yatu Avatar answered Jan 30 '23 23:01

yatu