29

Hi I have a list flat which is length 2800, it contains 100 results for each of 28 variables: Below is an example of 4 results for 2 variables

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

I would like to reshape the list to an array (2,4) so that the results for each variable are in a single element.

[[0,1,2,3],
 [0,1,2,3]]
BenP
  • 825
  • 1
  • 10
  • 30
  • 1
    The examples you provide are inconsistent: (1) you cannot reshape a list with 8 elements into a 2x2 array. (2) what is `np.shape = (28, 100)` supposed to do? – MB-F Feb 16 '16 at 12:32

4 Answers4

47

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

If you want to fill an array by column instead, an easy solution is to shape the list into an array with reversed dimensions and then transpose it:

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

Above snippet results in a 28x100 array, filled column-wise.

To illustrate, here are the two options of shaping a list into a 2x4 array:

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]])
MB-F
  • 22,770
  • 4
  • 61
  • 116
  • 1
    I have used this solution, but ran into a problem when the size of the list is not a multiple of the number of columns. My solution was to add empty itens to the list, using "+" for list concatenation. To calculate the number of elements to do add, I did `newlist = list+(c-N%c)*[""]`, where `c` is the number of columns and `N` is the length of the list. You could use `["0"]` instead of `[""]` for numeric (homogeneous) arrays. – Hugo Cavalcante Sep 30 '21 at 16:42
  • @HugoCavalcante With `c - N%c` it will add a whole row if the list size is an exact multiple of the column number. You can avoid that by using `(-N)%c` instead. – MB-F Oct 01 '21 at 06:44
3

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
2

Step by step:

# import numpy library
import numpy as np
# create list
my_list = [0,0,1,1,2,2,3,3]
# convert list to numpy array
np_array=np.asarray(my_list)
# reshape array into 4 rows x 2 columns, and transpose the result
reshaped_array = np_array.reshape(4, 2).T 

#check the result
reshaped_array
array([[0, 1, 2, 3],
       [0, 1, 2, 3]])
cristiandatum
  • 329
  • 2
  • 10
1

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 maybe not efficient in case of very large numbers. But it works for small set of numbers. Thanks

Ibrahim
  • 798
  • 6
  • 26
Vinay Verma
  • 877
  • 8
  • 15