Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reshape list to ndim array

Tags:

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]] 
like image 496
BenP Avatar asked Feb 16 '16 12:02

BenP


People also ask

How do you reshape an array list in Python?

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.

How do you change the shape of a list in Python?

A simple and naive method is to use a for loop and Python extended slices to append each sublist of list2 to a variable 'res'. Another method is to use islice function from itertools module. islice selectively prints the values mentioned in its iterable container.

What is the use of reshape (- 1 1 in Python?

Artturi Jalli. In NumPy, -1 in reshape(-1) refers to an unknown dimension that the reshape() function calculates for you. It is like saying: “I will leave this dimension for the reshape() function to determine”. A common use case is to flatten a nested array of an unknown number of elements to a 1D array.


1 Answers

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]]) 
like image 177
MB-F Avatar answered Sep 30 '22 20:09

MB-F