numpy.reshape() in PythonThe numpy.reshape() function is available in NumPy package. As the name suggests, reshape means 'changes in shape'. The numpy.reshape() function helps us to get a new shape to an array without changing its data. Sometimes, we need to reshape the data from wide to long. So in this situation, we have to reshape the array using reshape() function. SyntaxParametersThere are the following parameters of reshape() function: 1) arr: array_like This is a ndarray. This is the source array which we want to reshape. This parameter is essential and plays a vital role in numpy.reshape() function. 2) new_shape: int or tuple of ints The shape in which we want to convert our original array should be compatible with the original array. If an integer, the result will be a 1-D array of that length. One shape dimension can be -1. Here, the value is approximated by the length of the array and the remaining dimensions. 3) order: {'C', 'F', 'A'}, optional These indexes order parameter plays a crucial role in reshape() function. These index orders are used to read the elements of source array and place the elements into the reshaped array using this index order.
ReturnsThis function returns a ndarray. It is a new view object if possible; otherwise, it will be a copy. There is no guarantee of the memory layout of the returned array. Example 1: C-like index orderingOutput: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In the above code
In the output, the array has been represented as three rows and four columns. Example 2: Equivalent to C ravel then C reshapeThe ravel() function is used for creating a contiguous flattened array. A one-dimensional array that contains the elements of the input, is returned. A copy is made only when it is needed. Output: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) Example 3: Fortran-like index orderingOutput: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]]) In the above code
In the output, the array has been represented as four rows and three columns. Example 4: Fortran-like index orderingOutput: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]]) Example 5: The unspecified value is inferred to be 2In the above code
In the output, the array has been represented as two rows and five columns. Output: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11]]) Next Topicnumpy.sum() in Python |