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?
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]]
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()
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