QNA > W > What Does Reshaping An Array In Python With One Dimension Set To -1 Do?

What does reshaping an array in Python with one dimension set to -1 do?

Aloha!!

According to numpy docs -

Once the shape dimension can be -1, the value is offered from the length of the array and remaining dimension.

Let's see how the value of -1 is calculated.

Eg -

  1. import numpy as np 
  2. z = np.array([ 
  3. [1,2,3,4], 
  4. [5,6,7,8], 
  5. [9,10,11,12]]) 
  6.  
  7. z.shape=>(3,4) 
  8. z.size => 12 =>3*4 
  9. z.ndin=>2, z is 2d 

Now if .

  1. z.reshape(-1)  
  2. [ 1 2 3 4 5 6 7 8 9 10 11 12]  
  3. z.reshape(-1).ndim => 1 

Comments - z has been reduced to 1d array which equals to size of original array z. So -1 == 12(size of original z).

Now if.

  1. z.reshape((-1,1)) 
  2. [[ 1] 
  3. [ 2]  
  4. [ 3]  
  5. [ 4]  
  6. [ 5]  
  7. [ 6]  
  8. [ 7]  
  9. [ 8]  
  10. [ 9]  
  11. [10]  
  12. [11]  
  13. [12]]  

Comments -

  1. Now shape of z is (12,1).
  2. Passed value (-1,1)
  3. Calculation of -1 = size of z /column = 12/1 = 12
  4. So shape is (12,1).

Now if.

  1. z.reshape((-1,2)) 
  2. [[ 1 2] 
  3. [ 3 4]  
  4. [ 5 6]  
  5. [ 7 8]  
  6. [ 9 10]  
  7. [11 12]]  

Comments -

  1. Now shape of z is (6,2).
  2. Passed value(-1,2).
  3. Calculation of -1 = size of z /column = 12/2 = 6.
  4. So the shape is (6,2).

Now if.

  1. z.reshape((3,-1)) 
  2. [[ 1 2 3 4] 
  3. [ 5 6 7 8]  
  4. [ 9 10 11 12]]  

Comments -

  1. Now shape of z is (3 ,4).
  2. Passed size (3,-1)
  3. Calculation of -1 = size of z /row= 12/3 =4.
  4. So the shape is (3,4).

Now if.

  1. z.reshape((-1,-1))  
  2. ValueError: can only specify one unknown dimension  

Comments -

  1. Value error.
  2. Passed size (-1,-1).
  3. Calculation of -1 = 12/12 = 1
  4. Shape(1,1 ). A size 12 array cannot be reduced to shape (1,1). So we get the Error.

JD.

Di Ivory Oum

Quali sono le migliori app gratuite per le routine di esercizi HIIT / bodyweight? :: Quali sono le migliori applicazioni gratuite per l'editing video per un video YouTube di cucina?
Link utili