Python reshape list to ndim array

BenP picture BenP · Feb 16, 2016 · Viewed 97.1k times · Source

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]]

Answer

kazemakase picture kazemakase · Feb 16, 2016

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