Convert a 1D array to a 2D Numpy array
Numpy is a Python package that consists of multidimensional array objects and a collection of operations or routines to perform various operations on the array and processing of the array. This package consists of a function called numpy.reshape which is used to convert a 1-D array into a 2-D array of required dimensions (n x m). This function gives a new required shape without changing the data of the 1-D array.
Syntax: numpy.reshape(array, new_shape, order)
- array: is the given 1-D array that will be given a new shape or converted into 2-D array
- new_shape: is the required shape or 2-D array having int or tuple of int
- order: ‘C’ for C style, ‘F’ for Fortran style, ‘A’ if data is in Fortran style then Fortran like order else C style.
Before reshaping: [1 2 3 4 5 6 7 8] After reshaping having dimension 4x2: [[1 2] [3 4] [5 6] [7 8]] After reshaping having dimension 2x4: [[1 2 3 4] [5 6 7 8]]
Example 2: Let us see an important observation that whether we can reshape a 1-D array into any 2-D array.
This concludes that the number of elements should be equal to the product of dimension i.e. 3×3=9 but total elements = 8;
Example 3: Another example is that we can use the reshape method without specifying the exact number for one of the dimensions. Just pass -1 as the value and NumPy will calculate the number.
Before reshaping: [1 2 3 4 5 6 7 8] After reshaping: [[[1 2] [3 4]] [[5 6] [7 8]]]