# NumPy Array Reshape (Shape Transformation Without Data Change) – Like Geeks

In this tutorial, you will learn about reshaping the NumPy arrays. This tutorial focuses on the reshaping technique using the NumPy array reshape function. The shape of an array is defined as the total number of elements in each dimension of the array.

Reshaping an array means change either the number of elements in an array or changing the dimension of the array or both.
The reshape() method of the NumPy module is used to change an array’s shape without changing the data.

## How does NumPy reshape works?

The reshape() method of the NumPy module can change the shape of an array. For instance, you have a table with rows and columns; you can change the rows into columns and columns into rows.
Take a real example of an array with 12 columns and only 1 row.

You can reduce the columns from 12 to 4 and add the remaining data of the columns into new rows. As demonstrated in the figure below:

The NumPy reshaping technique lets us reorganize the data in an array. The numpy.reshape() method does not change the original array, rather it generates a view of the original array and returns a new (reshaped) array. The syntax for numpy.reshape() is given below:

Syntax:

```numpy.reshape(array, shape, order = ‘C’)
```
• array is the original array on which reshape() method will be applied.
• shape is the new shape. It should be compatible with the shape of the original array.
• order = ‘C’, the value of order can be A, C, or F. These alphabets represent the index order in which the array elements would be read.

The method reshape() will return a reshaped array with the same data.

## Reshape 1d to 2d

To convert 1D array to 2D array, call the reshape() function with 1D array as the input. Consider the following example in which we have a 1D array with ten elements.

We will convert this array into a 2D array such that the new array has two dimensions with five elements each or five columns.

Code:

```import numpy as npm

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

output_array = np.reshape(a, (2, 5))

print("2D array after converting: ", output_array)
```

Output:

The reshape() function takes the input array, then a tuple that defines the shape of the new array.

The shape (2, 5) means that the new array has two dimensions and we have divided ten elements of the input array into two sets of five elements.

Remember that the number of elements in the output array should be the same as in the input array.

## Reshape 1d to 3d

In the following example, we have twelve elements in the 1D input array. We have to divide the elements into three dimensions such that each dimension has four elements.

Code:

```import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

output_array = np.reshape(a, (3, 4))
```

Output:

## Reshape 2d to 1d

In the following code, we have a 2D array with four columns. The code below will reshape the array into one dimension containing all elements.

Code:

```import numpy as np

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

output_array = np.reshape(a, (1, 8))

print(output_array)

```

Output:

In the reshape() method, the tuple (1, 8) means a 1D output array with eight columns.

## Reshape 2d to 3d

The code below converts a 2D array to a 3D array with the same number of elements.

Code:

```import numpy as np

a = np.array([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]])

output_array = np.reshape(a, (3, 4))

print(output_array)
```

Output:

The new array has three dimensions with four columns or four elements in each dimension.

## Reshape 3d to 1d

The following code converts three dimensions of an array into one dimension.

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 6]])

output_array = np.reshape(a, (1, 9))

print(output_array)

```

Output:

## Rshape 3d to 2d

To convert a 3-dimensional array into 2D, consider the code below:

Code:

```import numpy as np

a = np.array([[1, 2], [6, 7], [4, 5]])

output_array = np.reshape(a, (2, 3))

print(output_array)

```

Output:

## Reshape 4d to 2d

To convert a 4D array to a 2D array, consider the following example:

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 9], [10, 11, 13]])

output_array = np.reshape(a, (2, 6))

print(output_array)
```

Output:

## Reshape with -1 (unknown dimension)

If you want to convert an array of an unknown dimension to a 1D array, use reshape(-1) as shown below:

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 6], [11, 14, 10]])

output_array = np.reshape(a, (-1))

print(output_array)
```

Output:

## Reshape 0d to 1d

An array with one dimension and length equals one is called a 0D array. In other words, a 0-dimensional array is a scalar quantity with a constant length of 1. In the following code we will reshape a 0-dimensional array to a 1-dimensional array:

Code:

```import numpy as np

a = np.array(1)

print("dimension of array a: ", a.ndim)

b = np.reshape(a, -1)

print("dimension of array b: ", b.ndim)

```

Output:

In the above example, first, we have created a 0-dimensional array. As a 0-dimensional array is a scalar quantity, therefore, there is only one item. We cannot add more than one item or any dimensions.

The ndim function tells the dimension of an array. Then we used reshape(-1) as in the previous heading to reshape the array to 1-dimension. Once the array is 1-dimensional, you can add elements to an array.

## Reshape reverse

In some cases, you need to reverse the shape of the array to its original dimensions.

If you applied the reshape() method to an array and you want to get the original shape of the array back, you can call the reshape function on that array again.

Reversing the shape of an array is demonstrated in the code below:

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 9], [10, 11, 13]])

output_array = np.reshape(a, (2,6))

original_array = np.reshape(output_array, (a.shape))

print(output_array)

print(original_array)

```

Output:

In this example, we have an array of four dimensions. Then we reshaped the array to two dimensions and stored the array in output_array.

On applying the reshape function on the output_array, we got our original array back with the same dimensions. Note that we have given the dimensions of the original array using the shape function.

You can also perform reverse reshape in one line of code as given below:

```output_array = np.reshape(a, (2,6)).reshape(a.shape)
```

## Reshape order

When using the reshape method to reshape arrays, there is a parameter called order in the syntax of reshape(). The order parameter decides in which index order elements will be fetched and arranged in the reshaped array.

The order parameter can have three values: C, F, and A.

• The order C means that the elements of the array will be reshaped with the last index changing the fastest. The order C performs row-wise operations on the elements.
• The order F means that the elements of the array will be reshaped with the first index changing the fastest. The order F performs column-wise operations on the elements of the array.
• The order A depends on how the array is stored in memory. If the array is stored in memory in F order, it will be reshaped following rules of order F. If the array is stored in memory in C order, the array will be reshaped following the rules of order C.

Consider the following example to see a clear picture of how index orders reshape an array.

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 9], [10, 11, 13]])

output_array = np.reshape(a, (2,6), order="C")

print (output_array)
#[[ 1  2  3  6  7  8]
#[ 4  5  9 10 11 13]]

output_array = np.reshape(a, (2,6), order="F")

print (output_array)
#[[ 1  4  2  5  3  9]
#[ 6 10  7 11  8 13]]
```

Output:

In the above example, in order C or the row-wise operation, the first two rows are combined and then the next two rows are merged. In the column-wise operation, the elements of first and third columns are read first.

In other words, C is row by row operation and F is column by column operation.

## Reshape along axes

Axes in an array are the directions along the columns and the rows of the array. In NumPy, axes and dimensions are considered the same. Axes are used to index an array.

In a multidimensional array, there is only one index per one axis. Check out the visual below:

Axis 1 is the direction along the columns and axis 0 is the direction along rows. For example, if you have an array:

```[[1, 2], [4, 5]]
```

We will use axes as [1, 1]. [1, 1] means row 1 and column 1. The NumPy reshape() method reshapes the array along 0 axis or 0-dimension that is along row.

We can change the row operation to column operation by specifying the order argument in the reshape() method. Consider the following example in which we have applied Order C and Order F.

Code:

```import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])

output_array = np.reshape(a, (2, 3), order="C")

print(output_array)
#[[1 2 3]
#[4 5 6]]

output_array = np.reshape(a, (2, 3), order="F")

print(output_array)
#[[1 5 4]
#[3 2 6]]
```

Output:

Therefore, order C reshaped the array along 0-dimension (row) and order F reshaped the array along 1-dimension (column).
Now let us use axes with NumPy reshape. Note that in NumPy, dimensions are axes. The following example shows how to specify the number of dimensions, number of rows, and number of columns in an array:

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 9], [10, 11, 13]])

output_array = np.reshape(a, (3, 4, 1))

print (output_array)
```

Output:

In this code, there are three arguments in the reshape() method. The first argument that is ‘3’ tells the number of dimensions in the array, the second argument that is ‘4’ specifies the number of rows and the third argument specifies the number of columns.

In other words, you can say that the outermost array has three arrays inside, each of the three arrays further contain four arrays, and all four arrays have one element.

## Reshape column to row

The reshape() method does not change column data to row, but it changes the shape of an array that is the dimensions of the array.

Therefore, we can only swap the dimensions of an array with the reshape() method.
For instance, if an array has four rows and three columns, we will reshape it in such a way that the new array has three rows and four columns.

The following example demonstrates how reshape swaps dimensions.

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 9], [10, 11, 13]])

a.shape
#(4, 3)

output_array = np.reshape(a, (3,4))

output_array.shape
#(3, 4)

print(output_array)
```

Output:

We used the transpose() function of NumPy to change column data to row data.

## Reshape row to column

In the same way, if an array has three rows and two columns, reshape will change the dimensions such that the new array has three columns and two rows. Consider the following code:

Code:

```import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])

a.shape
#(3, 2)

output_array = np.reshape(a, (2, 3))

output_array.shape
#(2, 3)
```

Output:

## Reshape uneven array

If an array is uneven, the reshape method won’t be able to fit all elements into a new array.

This is because the uneven array has an odd number of elements, when you try to reshape this type of array, there must be one element left to put into the new array. Therefore, an error will be thrown. Consider the following example:

Code:

```import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6, 7]])

output_array = np.reshape(a, (2, 3))
```

Output:

## Reshape an image

You can reshape an array of an image using the reshape method. First, you need to import the image and then convert the image into an array.

Then we will reshape the array and finally convert the reshaped array back to an image. We will apply the reshape() method to the following image:

Consider the example below:

Code:

```import numpy as np

from PIL import Image

image = np.array (Image.open('18-example.png').convert('L'))

print ("Original Shape", image.shape)

#Original Shape (1200, 1200)
grey_image= Image.fromarray(image).save('19-grey_example.png')
```

We have converted the image to greyscale to simplify reshaping. Then store the image array in a variable.

```newshape_image = np.reshape(image, (800, 1800))

print ("After Reshaping", newshape_image.shape)

#After Reshaping (800, 1800)
#Now convert the array back to image.
newshape_image_export = Image.fromarray(newshape_image).save('20-reshape_example.png')

```

Output:

## Reshape large arrays/throws error

When you do not specify the right dimensions to reshape an array, the reshape() method will throw an error. This problem usually occurs when you reshape an array of a large size.

For example, when reshaping the array of an image, the array is pretty large in size. Therefore, we need to choose appropriate dimensions to reshape the array.
In the last example, we had an array of shape (1200, 1200).

The size of the array was 1,440,000. Now we need to figure out the right dimensions to reshape the array. We will find the factors of 1200.

In the last example, we divided 1200 by 1.5 and multiplied 1200 by 1.5 that gave us 800 and 1800 respectively.
If we specify dimensions that are not equivalent to the size of the original array, reshape will give the following error:

### Memory Error

If you have an array of larger size, the reshape() method will throw a memory error. The memory error is thrown when you are short of RAM and you have to load the entire dataset into the memory.

A concept called batch processing was introduced to resolve memory errors.
In batch processing, the data is stored in the hard drive and is divided into small batches. The batches are then loaded into memory one by one. This way memory is not drained.

## NumPy reshape() Vs NumPy transpose()

The main difference between NumPy reshape() and transpose() is that reshape() gives a new shape to the array whereas, transpose inverts the axes.

The transpose method only changes rows into columns or columns to rows (inverting axes). The reshape method will take an input array and format the array into the given shape.

This shape can have any dimensions and any number of columns respecting the size of the array.
The following example explains the difference between reshape() and transpose():

Code:

```import numpy as np

a = np.array([[1, 2, 3], [6, 7, 8], [4, 5, 9], [10, 11, 13]])

output_array = np.reshape(a, (2,6))

print (output_array)
#[[ 1  2  3  6  7  8]
#[ 4  5  9 10 11 13]]

transpose_array = np.transpose(a)

print (transpose_array)
#[[ 1  6  4 10]
#[ 2  7  5 11]
#[ 3  8  9 13]]

```

Output:

In the above example, you can see that reshape() method changed the dimensions of the array from 4D to 2D and the number of columns from 3 to 6.
Whereas, transpose() is a constant function that only performs one operation that changes rows into columns and columns into rows.

## NumPy reshape() vs NumPy resize()

Both reshape() and resize() methods of the NumPy module are used to define a new size of an array. The main difference between the two methods is that the reshape() method does not make changes to the original array rather it returns a new array as an output.

Whereas, the resize() method makes changes directly to the original array and returns the original array. The following code examples clearly tell the difference between reshape() and resize():

Using reshape()

```import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])

np.reshape(a, (2, 3))

print ("Original Array: ", a)
```

Output:

In the above output, the original array remains the same.

Using resize()

```import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])

a.resize(2,3)

print ("Original array after resize: ", a)
```

Output:

As shown in the code above, the resize() method made changes to the original array. The resize() method does not return anything; whereas, the reshape() method returns a new array with new dimensions.

## NumPy reshape() vs NumPy flatten()

The reshape() method reshapes an array to another shape. The NumPy flatten() method as the name says flattens an array. The flatten() method converts an array of any dimension to 1-dimension. The syntax of flatten() is as follows:

Syntax:

```ndarray.flatten(order)
```

It will return a 1-dimensional array. It does not make changes to the original array.

• The order parameter can have four values: C, F, A, and K.
• C flattens the array along 0 dimension (row).
• F flattens the array along 1st dimension (column).
• Order A depends on how the array is stored in memory. If the array is stored in memory in F order, it will be flattened following rules of order F. If the array is stored in memory in C order, the array will be reshaped following the rules of order C.
• K flattens an array according to the order of elements stored in memory.

The following example explains how flatten() works:

Code:

```import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])

print("Flattened array: ", a.flatten())

print("Original array: ", a)
```

Output:

The flatten() method does not make changes to the original array. The input array was three-dimensional and is flattened to 1D using the flatten() method.

This article was originally posted on likegeeks.com. Read here

Share This
Scroll to Top