Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape an array in NumPy

Consider an array of the following form (just an example):

[[ 0  1]  [ 2  3]  [ 4  5]  [ 6  7]  [ 8  9]  [10 11]  [12 13]  [14 15]  [16 17]] 

It's shape is [9,2]. Now I want to transform the array so that each column becomes a shape [3,3], like this:

[[ 0  6 12]  [ 2  8 14]  [ 4 10 16]] [[ 1  7 13]  [ 3  9 15]  [ 5 11 17]] 

The most obvious (and surely "non-pythonic") solution is to initialise an array of zeroes with the proper dimension and run two for-loops where it will be filled with data. I'm interested in a solution that is language-conform...

like image 564
user1876864 Avatar asked Jan 23 '13 09:01

user1876864


People also ask

What is use of reshape () method in the NumPy?

The numpy. reshape() function shapes an array without changing the data of the array. Return Type: Array which is reshaped without changing the data.

What is the meaning of reshape (- 1 1?

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.

How do you reshape an existing array?

reshape() reshape() function is used to create a new array of the same size (as the original array) but of different desired dimensions. reshape() function will create an array with the same number of elements as the original array, i.e. of the same size as that of the original array.


2 Answers

a = np.arange(18).reshape(9,2) b = a.reshape(3,3,2).swapaxes(0,2)  # a:  array([[ 0,  1],        [ 2,  3],        [ 4,  5],        [ 6,  7],        [ 8,  9],        [10, 11],        [12, 13],        [14, 15],        [16, 17]])   # b: array([[[ 0,  6, 12],         [ 2,  8, 14],         [ 4, 10, 16]],         [[ 1,  7, 13],         [ 3,  9, 15],         [ 5, 11, 17]]]) 
like image 78
eumiro Avatar answered Sep 21 '22 08:09

eumiro


numpy has a great tool for this task ("numpy.reshape") link to reshape documentation

a = [[ 0  1]  [ 2  3]  [ 4  5]  [ 6  7]  [ 8  9]  [10 11]  [12 13]  [14 15]  [16 17]]  `numpy.reshape(a,(3,3))` 

you can also use the "-1" trick

`a = a.reshape(-1,3)` 

the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3

so yes.. this would also work: a = a.reshape(3,-1)

and this: a = a.reshape(-1,2) would do nothing

and this: a = a.reshape(-1,9) would change the shape to (2,9)

like image 41
Or_K Avatar answered Sep 19 '22 08:09

Or_K