Python: numpy.reshape() function Tutorial with examples

In this article we will discuss how to use numpy.reshape() to change the shape of a numpy array.

numpy.reshape()

Python’s numpy module provides a function reshape() to change the shape of an array,

numpy.reshape(a, newshape, order='C')

Parameters:

  • a: Array to be reshaped, it can be a numpy array of any shape or a list or list of lists.
  • newshape: New shape either be a tuple or an int.
      • For converting to shape of 2D or 3D array need to pass tuple
      • For creating an array of shape 1D, an integer needs to be passed.
  • order: The order in which items from input array will be used,
      • ‘C’: Read items from array row wise i.e. using C-like index order.
      • ‘F’: Read items from array column wise i.e. using Fortran-like index order.
      • ‘A’: Read items from array based on memory order of items

It returns a new view object if possible, otherwise returns a copy. But in most scenario it returns a view and therefore it is very good in performance with big arrays.

Let’s understand this with more examples,

First, import the numpy module,

import numpy as np

Converting shapes of Numpy arrays using numpy.reshape()

Use numpy.reshape() to convert a 1D numpy array to a 2D Numpy array

Let’s first create a 1D numpy array from a list,

# Create a 1D Numpy array of size 9 from a list
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Now suppose we want to convert this 1D array to a 2D numpy array or matrix of shape (3X3) i.e. 3 rows and 3 columns. Let’s see how to do that using reshape(),

# Convert a 1D Numpy array to a 2D Numpy array
arr2D = np.reshape(arr, (3,3))

print('2D Numpy array')
print(arr2D)

Output:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

We passed the array and a tuple (shape) as arguments to the numpy.reshape() function and it returned a new 2D view of the passed array.

New shape must be compatible with the original shape

The new shape provided in reshape() function must be compatible with the shape of the array passed.
Suppose if we are trying to convert a 1D array of length N to a 2D Numpy array of shape (R,C), then R * C must be equal to N, otherwise it will raise an error. For example,

  • We can convert a numpy array of 9 elements to a 3X3 matrix or 2D array.
  • We can convert a numpy array of 12 elements to a 2X6 matrix or 6X2 matrix or 4X3 matrix or 3&4 matrix.
  • If we try to convert it to a matrix of any other shape then it will raise an error,

Let’s checkout an example or incompatible conversion

arr2D = np.reshape(arr, (3, 2))

Error,

ValueError: cannot reshape array of size 9 into shape (3,2)

We tried to create a matrix / 2D array of shape (3,2) i.e. 6 elements but our 1D numpy array had 9 elements only therefore it raised an error,

Using numpy.reshape() to convert a 1D numpy array to a 3D Numpy array

To convert a 1D Numpy array to a 3D Numpy array, we need to pass the shape of 3D array as a tuple along with the array to the reshape() function as arguments

We have a 1D Numpy array with 12 items,

# Create a 1D Numpy array of size 9 from a list
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

Now let’s convert this 1D array to a 3D numpy array of shape (2X3X2),

# Convert a 1D Numpy array to a 3D Numpy array of shape 2X3X2
arr3D = np.reshape(arr, (2, 3, 2))

print(arr3D)

Output:

[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]

Till now we have seen examples where we converted 1D array to either 2D or 3D. But using reshape() function we can convert an array of any shape to any other shape. Like,

Use numpy.reshape() to convert a 3D numpy array to a 2D Numpy array

Suppose we have a 3D Numpy array of shape (2X3X2),

# Create a 3D numpy array
arr3D = np.array([[[1, 2],
                   [3, 4],
                   [5, 6]],
                 [[11, 12],
                  [13, 14],
                  [15, 16]]])

Let’s convert this 3D array to a 2D array of shape 2X6 using reshape() function,

# Convert 3D numpy array to a 2D Numpy array of shape 2X6
arr2D = np.reshape(arr3D, (2,6))

print('2D Numpy Array')
print(arr2D)

Output:

2D Numpy Array
[[ 1  2  3  4  5  6]
 [11 12 13 14 15 16]]

Use numpy.reshape() to convert a 2D numpy array to a 1D Numpy array

Suppose we have a 2D Numpy array of shape (3X3),

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

Let’s convert this 2D array to a 1D array,

print('What does -1 mean in numpy reshape?')

# Covert multi dimension array to 1D array
flat_arr = np.reshape(arr, -1)

print(flat_arr)

Output:

[0 1 2 3 4 5 6 7 8]

If we pass -1 as the shape argument to the function reshape() then it will convert the array of any shape to a flat array.

numpy.reshape() returns a new view object if possible

Whenever possible numpy.reshape() returns a view of the passed object. If we modify any data in the view object then it will be reflected in the main object and vice-versa. Let’s understand this with an example,

Suppose we have a 1D numpy array,

# create a 1D Numpy array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

let’s create a 2D view object of the 1D Numpy array using reshape(),

# Get a View object of different shape i.e. 2D or matrix
arr2D = np.reshape(arr, (3,3))

print(arr2D)

Output:

[[1 2 3],
 [4 5 6],
 [7 8 9]]

Now modify the second element in the original 1D numpy array.

# Modify the 2nd element in the original array
# but changes will also be visible in the view object i.e. 2D array
arr[1] = 10

Although we modified the 1D array only but this change should be visible in the 2D view object too. Let’s confirm this,

print('1D Array:')
print(arr)

print('2D Array:')
print(arr2D)

Output:

1D Array:
[ 1 10  3  4  5  6  7  8  9]
2D Array:
[[ 1 10  3]
 [ 4  5  6]
 [ 7  8  9]]

This proves that in the above example reshape() returned a view object. But there might be scenarios when reshape() would not be able to return a view object. But how to identify if the returned value is a view or not ?

How to check if reshape() returned a view object ?

Whatever object reshape() returns, we can check its base attribute to confirm if its view or not. If base attribute is None then it is not a view object, whereas if is not None then it is a view object and base attributes points to the original array object i.e.,

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
arr2D = np.reshape(arr, (3, 3))

if arr2D.base is not None:
    print('arr2D is a view of arr')
    print('base array : ', arr2D.base)

Output:

arr2D is a view of arr
base array :  [1 2 3 4 5 6 7 8 9]

numpy.reshape() & different type of order parameters

In the reshape() function we can pass the order parameter too and its value can be ‘C’ o ‘F’ or ‘A’. Default value is ‘C’ . This parameter decides the order in which elements from the input array will be used.

Let’s understand this with an example,

Suppose we have a 1D array,

# create a 1D Numpy array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Convert 1D to 2D array row wise with order ‘C’

When we pass the order parameter as ‘C’ (default value of order parameter), then items from input array will be read row wise i.e.

# Covert 1D numpy array to 2D by reading items from input array row wise
arr2D = np.reshape(arr, (3, 3), order = 'C')

print(arr2D)

Output:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

Items from 1D array were read row wise i.e.

  • For 1st row of 2D array items from index 0 to 2 were read
  • For 2nd row of 2D array items from index 3 to 5 were read
  • For 2nd row of 2D array items from index 5 to 8 were read

Convert 1D to 2D array column wise with order ‘F’

When we pass the order parameter as ‘F’, then items from input array will be read column wise i.e.

# Covert 1D numpy array to 2D by reading items from input array column wise
arr2D = np.reshape(arr, (3, 3), order = 'F')

print(arr2D)

Output:

[[1 4 7]
 [2 5 8]
 [3 6 9]]

Items from 1D array were read column wise i.e.

  • For 1st Column of 2D array items from index 0 to 2 were read
  • For 2nd Column of 2D array items from index 3 to 5 were read
  • For 2nd Column of 2D array items from index 5 to 8 were read

Convert 1D to 2D array by memory layout with parameter order “A”

Both ‘C’ and ‘F’ options do not consider the memory layout of the input array. Whereas, when we pass the order parameter as ‘A’, then items from the input array will be read based on internal memory layout. Let’s understand by an example,

Create a 1D numpy array

# create a 1D Numpy array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Create a 2D view object from this 1D numpy array and then get a transpose view object of that 2D array,

# Create a 2D vew object and get transpose view of that
arr2D = np.reshape(arr, (3, 3)).T

print('2D & transposed View:')
print(arr2D)

Output:

[[1 4 7]
 [2 5 8]
 [3 6 9]]

Now let’s convert this transposed view object to a 1D numpy array using order ‘C’ i.e. row wise based on current shape.

flat_arr = np.reshape(arr2D, 9, order='C')
print(flat_arr)

Output:

[1 4 7 2 5 8 3 6 9]

It read the elements row wise from the current shape of the view object and the memory layout of the original array was not considered. Now let’s convert this transposed view object to a 1D numpy array using order ‘A’ i.e. based on memory layout of original array,

flat_arr = np.reshape(arr2D, 9, order='A')
print(flat_arr)

Output:

[1 2 3 4 5 6 7 8 9]

It reads the elements row wise from the based on the memory layout of the original 1D array. It does not consider the current view of the input array i.e. a view object.

Convert the shape of a list using numpy.reshape()

In reshape() function we can pass a list too instead of array.For example, let’s use reshape() function to convert a list to 2D numpy array,

list_of_num = [1,2,3,4,5,6,7,8,9]

# Convert a list to 2D Numpy array
arr2D = np.reshape(list_of_num, (3,3))

print('2D Array:')
print(arr2D)

Output:

2D Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Now let’s convert this 2D numpy array to a list of list,

# Convert 2D Numpy array to list of list
list_of_list = [ list(elem) for elem in arr2D]

print('List of List')
print(list_of_list)

Output:

List of List
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The complete example is as follows,

import numpy as np

def main():

    print('*** Using numpy.reshape() to convert a 1D numpy array to a 2D Numpy array ***')

    # Create a 1D Numpy array of size 9 from a list
    arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

    print('1D Numpy Array:')
    print(arr)

    # Convert a 1D Numpy array to a 2D Numpy array
    arr2D = np.reshape(arr, (3,3))

    print('2D Numpy array')
    print(arr2D)

    print('*** New shape must be compatible with the original shape ***')
    #arr2D = np.reshape(arr, (3, 2))

    print('**** Using numpy.reshape() to convert a 1D numpy array to a 3D Numpy array ****')

    # Create a 1D Numpy array of size 9 from a list
    arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

    # Convert a 1D Numpy array to a 3D Numpy array of shape 2X3X2
    arr3D = np.reshape(arr, (2, 3, 2))

    print('3D Numpy Array')
    print(arr3D)

    print('Using numpy.reshape() to convert a 3D numpy array to a 2D Numpy array')

    # Create a 3D numpy array
    arr3D = np.array([[[1, 2],
                       [3, 4],
                       [5, 6]],
                     [[11, 12],
                      [13, 14],
                      [15, 16]]])

    print('3D Numpy Array')
    print(arr3D)

    # Convert 3D numpy array to a 2D Numpy array of shape 2X6
    arr2D = np.reshape(arr3D, (2,6))

    print('2D Numpy Array')
    print(arr2D)

    print('Using numpy.reshape() to convert a 2D numpy array to a 1D Numpy array')

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

    flat_arr = np.reshape(arr, 9)

    print(flat_arr)

    print('What does -1 mean in numpy reshape?')
    flat_arr = np.reshape(arr, -1)
    print(flat_arr)

    print('**** numpy.reshape() returns a new view object if possible ****')

    # create a 1D Numpy array
    arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

    # Get a View object of different shape i.e. 2D or matrix
    arr2D = np.reshape(arr, (3,3))

    # Modify the 2nd element in the original array
    # but changes will also be visible in the view object i.e. 2D array
    arr[1] = 10

    print('1D Array:')
    print(arr)

    print('2D Array:')
    print(arr2D)

    print('** How to check if reshape() returned a view object ? **')

    arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    arr2D = np.reshape(arr, (3, 3))

    if arr2D.base is not None:
        print('arr2D is a view of arr')
        print('base array : ', arr2D.base)

    print('**** numpy.reshape() & different type of order parameters ****')

    # create a 1D Numpy array
    arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

    print('**Convert 1D to 2D array row wise with order "C" **')

    # Covert 1D numpy array to 2D by reading items from input array row wise
    arr2D = np.reshape(arr, (3, 3), order = 'C')

    print(arr2D)

    print('** Convert 1D to 2D array column wise with order "F" **')

    # Covert 1D numpy array to 2D by reading items from input array column wise
    arr2D = np.reshape(arr, (3, 3), order = 'F')

    print(arr2D)

    print('Convert 1D to 2D array by memory layout with parameter order "A" ')

    # create a 1D Numpy array
    arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

    # Create a 2D vew object and get transpose view of that
    arr2D = np.reshape(arr, (3, 3)).T

    print('2D & transposed View:')
    print(arr2D)

    print('1D View of transposed array using order parameter C i.e. row wise')

    flat_arr = np.reshape(arr2D, 9, order='C')
    print(flat_arr)

    print('1D View of transposed array using order parameter F i.e. based on memory layout')
    flat_arr = np.reshape(arr2D, 9, order='A')
    print(flat_arr)

    print('**** Convert the shape of a list using numpy.reshape() ****')

    list_of_num = [1,2,3,4,5,6,7,8,9]

    # Convert a list to 2D Numpy array
    arr2D = np.reshape(list_of_num, (3,3))

    print('2D Array:')
    print(arr2D)

    # Convert 2D Numpy array to list of list
    list_of_list = [ list(elem) for elem in arr2D]

    print('List of List')
    print(list_of_list)

if __name__ == '__main__':
    main()

Output

*** Using numpy.reshape() to convert a 1D numpy array to a 2D Numpy array ***
1D Numpy Array:
[1 2 3 4 5 6 7 8 9]
2D Numpy array
[[1 2 3]
 [4 5 6]
 [7 8 9]]
*** New shape must be compatible with the original shape ***
**** Using numpy.reshape() to convert a 1D numpy array to a 3D Numpy array ****
3D Numpy Array
[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]
Using numpy.reshape() to convert a 3D numpy array to a 2D Numpy array
3D Numpy Array
[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[11 12]
  [13 14]
  [15 16]]]
2D Numpy Array
[[ 1  2  3  4  5  6]
 [11 12 13 14 15 16]]
Using numpy.reshape() to convert a 2D numpy array to a 1D Numpy array
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[0 1 2 3 4 5 6 7 8]
What does -1 mean in numpy reshape?
[0 1 2 3 4 5 6 7 8]
**** numpy.reshape() returns a new view object if possible ****
1D Array:
[ 1 10  3  4  5  6  7  8  9]
2D Array:
[[ 1 10  3]
 [ 4  5  6]
 [ 7  8  9]]
** How to check if reshape() returned a view object ? **
arr2D is a view of arr
base array :  [1 2 3 4 5 6 7 8 9]
**** numpy.reshape() & different type of order parameters ****
**Convert 1D to 2D array row wise with order "C" **
[[1 2 3]
 [4 5 6]
 [7 8 9]]
** Convert 1D to 2D array column wise with order "F" **
[[1 4 7]
 [2 5 8]
 [3 6 9]]
Convert 1D to 2D array by memory layout with parameter order "A" 
2D & transposed View:
[[1 4 7]
 [2 5 8]
 [3 6 9]]
1D View of transposed array using order parameter C i.e. row wise
[1 4 7 2 5 8 3 6 9]
1D View of transposed array using order parameter F i.e. based on memory layout
[1 2 3 4 5 6 7 8 9]
**** Convert the shape of a list using numpy.reshape() ****
2D Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
List of List
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top