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