Contents

## NumPy – Reshape Array

To reshape a given array to specific shape using NumPy library, we can use numpy.reshape() function.

Pass the given array, and required shape (as tuple) as arguments to the numpy.reshape() function.

## Examples

In the following program, we reshape a numpy array of shape (3, 4) to (2, 6).

**Python Program**

```
import numpy as np
# reshape (3, 4) array to (6, 2)
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
shape = (6, 2)
output = np.reshape(arr, shape)
print(output)
```

Run **Output**

```
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
```

If any of the dimension in the input shape is given as -1, then this dimension is adjusted based on the length in other dimensions.

For example, in the following program, we reshape a numpy array of shape (3, 4) to (-1, 2). Since we have -1 for the first dimension in the output shape, that dimension’s length is computed from `(3*4)/(2)`

which is `6`

.

**Python Program**

```
import numpy as np
# reshape (3, 4) array to (6, 2)
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
shape = (-1, 2)
output = np.reshape(arr, shape)
print(output)
```

Run **Output**

```
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
```

## Summary

In this tutorial of Python Examples, we learned how to reshape a given numpy array in Python using numpy.reshape() function.