Reputation: 5938
I have a feeling that this is very easy but I can't quite figure out how to do it. Say I have a Numpy array
[1,2,3,4]
How do I convert this to
[[1],[2],[3],[4]]
In an easy way?
Thanks
Upvotes: 2
Views: 1711
Reputation: 361
>>> A = [1,2,3,4]
>>> B = [[x] for x in A]
>>> print B
[[1], [2], [3], [4]]
Upvotes: 1
Reputation: 250871
You can use numpy.reshape:
>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> np.reshape(a, (-1, 1))
array([[1],
[2],
[3],
[4]])
If you want normal python list then use list comprehension
:
>>> a = np.array([1,2,3,4])
>>> [[x] for x in a]
[[1], [2], [3], [4]]
Upvotes: 2
Reputation: 7822
The most obvious way that comes to mind is:
>>> new = []
>>> for m in a:
new.append([m])
but this creates normal Python's list of lists, I'm not sure if this is what you want...
Upvotes: 1
Reputation: 86128
You can use np.newaxis
:
>>> a = np.array([1,2,3,4]
array([1, 2, 3, 4])
>>> a[:,np.newaxis]
array([[1],
[2],
[3],
[4]])
Upvotes: 3