2

So I currently have a numpy array like

[[0, 1, 2, 3, 4]]

but I want it to be

[[0],[1],[2],[3],[4]]

Is there a list comprehension method to do so?

Matthew Li
  • 21
  • 2

3 Answers3

3

Using either reshape or translate T you can do:

a = np.array([[0, 1, 2, 3, 4]])

a.reshape(a.size, 1)

or

a.T

With the result being:

array([[0],
       [1],
       [2],
       [3],
       [4]])
Luca Cappelletti
  • 2,485
  • 20
  • 35
3

Your first array can be created by

array1 = np.arange(5).reshape((1,5))

Printing array1 gives

[[0 1 2 3 4]]

You can reshape that with

array2 = array1.reshape((5,1))

Printing that gives

[[0]
 [1]
 [2]
 [3]
 [4]]

Or, as @LucaCappelletti typed before I could,

array2 = array1.T

That T means "transpose," swapping the columns and the rows of a 2-dimensional matrix. This is simpler but is more error-prone if array1 is not just what you think it is. Yet another way is

array2 = array1.transpose()

which is basically a synonym for T.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
0

I heard you say list comprehension :) Here you go

a = [[0, 1, 2, 3, 4]]
a_new = [[i] for i in a[0]]
print (a_new)
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • 1
    Who is downvoting the solution which the OP asked for specifically. If it's about `list` versus `array` definition of `a`, that's no reason to downvote. Downvoting without reasoning is just immature. OP clearly asked for *list comprehension method* – Sheldore Aug 03 '18 at 23:57