Avii
Avii

Reputation: 164

How to convert a list to an array as there is a need to take transpose in Python?

I have a u0 list in which values are appended, and then I have to take the transpose of u0, but when I am doing this, I still get a row matrix, but I want to show it as a column matrix. From other answers, I learned that there would be no difference in calculations, but I want it to be shown as column matrix and this can be used further for calculations. x_mirror is also a list.

u0 = []
for p in range(0,tpts):                              #initial condition at t = 0
    ts =  ((np.exp(alpha*((x_mirror[p]-x_start)**2))*(np.cos(k0*(x_mirror[p]-x_start)))))
    u0.append(ts)

Any help is highly appreciated.

Upvotes: 0

Views: 82

Answers (4)

Mortz
Mortz

Reputation: 4879

You can use reshape -

u0 = [1, 2, 3]
np_u0_row = np.array(u0)
np_u0_col = np_u0_row.reshape((1, len(u0)))
print(np_u0_col.shape)
# (1, 3)

Upvotes: 1

Shankar
Shankar

Reputation: 126

Based on an already existing stackoverflow post (here) you can do the following to

import numpy as np
list1 = [2,4,6,8,10]

array1 = np.array(list1)[np.newaxis]
print(array1)
print(array1.transpose())

For the above code you can see the output here:

enter image description here

Upvotes: 3

James
James

Reputation: 36608

If you just want it to display vertically, you can create your class as a subclass of list.

class ColumnList(list):
    def __repr__(self):
        parts = '\n '.join(map(str, self))
        r = f'[{parts}]'
        return r

u0 = ColumnList()
for p in range(0,tpts):                              #initial condition at t = 0
    ts =  ((np.exp(alpha*((x_mirror[p]-x_start)**2))*(np.cos(k0*(x_mirror[p]-x_start)))))
    u0.append(ts)

# displays vertically:
u0

Upvotes: 1

fhirsch
fhirsch

Reputation: 9

Not sure if I got the question right, but try to convert it into a 2-dimensional Array with the right number of rows and only one column.

rowMatrix = [1, 2, 3, 4, 5]
columnMatrix = [[1], [2], [3], [4], [5]]

Upvotes: -1

Related Questions