Home > database >  Struggling to reshape an odd array
Struggling to reshape an odd array

Time:02-01

I am struggling with a problem from my python class that has been assigned where I have to create a 1D array with the arange function from 0 to 29. Then reshape it into:

  1. An array of rank 2 of the appropriate size.
  2. An array of rank 3 of the appropriate size.

I am able to create the array with z = np.arange(29), however I am unable to reshape it to be a 2d/3d array.

z = np.arange(29)
print(z.shape)
z = z.reshape(2,14)

But then I get an error saying:

ValueError:cannot reshape array of size 29 into shape (2,14)

CodePudding user response:

While the specification is a bit ambiguous, I suspect they want you to generate 30 numbers that include 0 and 29:

In [73]: arr = np.arange(30)
In [74]: arr
Out[74]: 
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29])
In [75]: arr.shape
Out[75]: (30,)

There many ways you can reshape this, all of which assume 30 values:

In [76]: arr.reshape(2,15)
Out[76]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])

In [77]: arr.reshape(3,10)
Out[77]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])

In [79]: arr.reshape(2,3,5)
Out[79]: 
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14]],

       [[15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29]]])

CodePudding user response:

Proposed solution based on comments.

Assumption is the that the array should include the numbers from 0 to 28, but it doesn't necessarily have to be of size 29. This allows us to add np.nan as the 30th element allowing the reshape.

import numpy as np

x = np.arange(29)
x = np.append(x, np.nan)
print(x.shape)

y = x.reshape(15, 2)
print(y.shape)

z = x.reshape(5, 3, 2)
print(z.shape)

output:

(30,)
(15, 2)
(5, 3, 2)
  •  Tags:  
  • Related