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

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]])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

1
>>> A = [1,2,3,4]

>>> B = [[x] for x in A]

>>> print B
[[1], [2], [3], [4]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.