Python reshape list to ndim array Python reshape list to ndim array numpy numpy

Python reshape list to ndim array


You can think of reshaping that the new shape is filled row by row (last dimension varies fastest) from the flattened original list/array.

An easy solution is to shape the list into a (100, 28) array and then transpose it:

x = np.reshape(list_data, (100, 28)).T

Update regarding the updated example:

np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (4, 2)).T# array([[0, 1, 2, 3],#        [0, 1, 2, 3]])np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (2, 4))# array([[0, 0, 1, 1],#        [2, 2, 3, 3]])


Step by step:

# import numpy libraryimport numpy as np# create listmy_list = [0,0,1,1,2,2,3,3]# convert list to numpy arraynp_array=np.asarray(my_list)# reshape array into 4 rows x 2 columns, and transpose the resultreshaped_array = np_array.reshape(4, 2).T #check the resultreshaped_arrayarray([[0, 1, 2, 3],       [0, 1, 2, 3]])


The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.

You can run a small loop and change the dimension from 1xN to Nx1.

    tmp=[]    for b in bus:        tmp.append([b])    bus=tmp

It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers.Thanks