2

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

asked Jul 4, 2013 at 19:26
2
  • To be precise: you're trying to convert np.array([1, 2, 3, 4]) to np.array([[1], [2], [3], [4]])? Or convert it to a traditional Python list of lists? Commented Jul 4, 2013 at 19:28
  • oh sorry. Numpy array. Commented Jul 4, 2013 at 19:44

4 Answers 4

3

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]])
answered Jul 4, 2013 at 19:31
2

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]]
answered Jul 4, 2013 at 19:28
1

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...

answered Jul 4, 2013 at 19:35
1
>>> A = [1,2,3,4]
>>> B = [[x] for x in A]
>>> print B
[[1], [2], [3], [4]]
answered Jul 4, 2013 at 19:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.