Skip to content

How to Dynamically Change Dimensions in Python

[

Using NumPy reshape() to Change the Shape of an Array

by Stephen Gruppetta

The main data structure that you’ll use in NumPy is the N-dimensional array. An array can have one or more dimensions to structure your data. In some programs, you may need to change how you organize your data within a NumPy array. You can use NumPy’s reshape() to rearrange the data.

The shape of an array describes the number of dimensions in the array and the length of each dimension. In this tutorial, you’ll learn how to change the shape of a NumPy array to place all its data in a different configuration. When you complete this tutorial, you’ll be able to alter the shape of any array to suit your application’s needs.

In this tutorial, you’ll learn how to:

  • Change the shape of a NumPy array without changing its number of dimensions
  • Add and remove dimensions in a NumPy array
  • Control how data is rearranged when reshaping an array with the order parameter
  • Use a wildcard value of -1 for one of the dimensions in reshape()

For this tutorial, you should be familiar with the basics of NumPy and N-dimensional arrays. You can read NumPy Tutorial: Your First Steps Into Data Science in Python to learn more about NumPy before diving in.

Install NumPy

You’ll need to install NumPy to your environment to run the code in this tutorial and explore reshape(). You can install the package using pip within a virtual environment. Select either the Windows or Linux + macOS tab below to see instructions for your operating system:

Windows PowerShell

Terminal window
PS> python -m venv venv
PS> .\venv\Scripts\activate
(venv) PS> python -m pip install numpy

Shell

Terminal window
$ python -m venv venv
$ source venv/bin/activate
(venv) $ python -m pip install numpy

It’s a convention to use the alias np when you import NumPy. To get started, you can import NumPy in the Python REPL:

Python

>>> import numpy as np

Now that you’ve installed NumPy and imported the package in a REPL environment, you’re ready to start working with NumPy arrays.

Understand the Shape of NumPy Arrays

You’ll use NumPy’s ndarray in this tutorial. In this section, you’ll review the key features of this data structure, including an array’s overall shape and number of dimensions.

You can create an array from a list of lists:

Python

>>> import numpy as np
>>> numbers = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> numbers
array([[1, 2, 3, 4],
[5, 6, 7, 8]])

To understand the shape of this array, you can use the shape attribute:

Python

>>> numbers.shape
(2, 4)

This tells you that the array has 2 rows and 4 columns.

Change an Array’s Shape Using NumPy reshape()

You can use the reshape() function to change the shape of an array. This function takes in the array and the desired shape as arguments. It returns a new array with the specified shape.

Here’s an example:

Python

>>> import numpy as np
>>> numbers = np.array([1, 2, 3, 4, 5, 6])
>>> reshaped_numbers = numbers.reshape(2, 3)
>>> reshaped_numbers
array([[1, 2, 3],
[4, 5, 6]])

In this example, the original array numbers had 6 elements. By reshaping it to a 2x3 array, the elements are rearranged accordingly.

Reduce an Array’s Number of Dimensions

You can also use reshape() to reduce the number of dimensions in an array. For example, if you have a 2D array, you can reshape it to a 1D array:

Python

>>> import numpy as np
>>> numbers = np.array([[1, 2, 3], [4, 5, 6]])
>>> reshaped_numbers = numbers.reshape(6)
>>> reshaped_numbers
array([1, 2, 3, 4, 5, 6])

The original array had 2 rows and 3 columns. By reshaping it to a 1D array, the dimensions are reduced, and the elements are now in a single row.

Increase an Array’s Number of Dimensions

On the other hand, you can also use reshape() to increase the number of dimensions in an array. For example, if you have a 1D array, you can reshape it to a 2D array:

Python

>>> import numpy as np
>>> numbers = np.array([1, 2, 3, 4, 5, 6])
>>> reshaped_numbers = numbers.reshape(2, 3)
>>> reshaped_numbers
array([[1, 2, 3],
[4, 5, 6]])

The original array had 6 elements. By reshaping it to a 2x3 array, the dimensions are increased, and the elements are organized accordingly.

Ensure the Shape of the New Array Is Compatible With the Original Array

When using reshape(), it’s important to ensure that the shape of the new array is compatible with the original array. In other words, the total number of elements in both arrays should be the same.

For example, if you have a 1D array with 6 elements, you can reshape it to a 2x3 array or a 3x2 array, but you cannot reshape it to a 2x2 array because that would require 4 elements.

Python

>>> import numpy as np
>>> numbers = np.array([1, 2, 3, 4, 5, 6])
>>> reshaped_numbers = numbers.reshape(2, 3) # Valid reshaping
>>> reshaped_numbers_incompatible = numbers.reshape(2, 2) # Invalid reshaping
ValueError: cannot reshape array of size 6 into shape (2,2)

Control How the Data Is Rearranged Using order

When reshaping an array, you can also control how the data is rearranged using the order parameter. This parameter accepts different values, including 'C' (default) and 'F'.

By default, NumPy uses 'C' order, which means it arranges the data in row-major order. This means that the elements of each row are contiguous in memory.

If you want to arrange the data in column-major order, you can use 'F' order:

Python

>>> import numpy as np
>>> numbers = np.array([[1, 2, 3], [4, 5, 6]])
>>> reshaped_numbers = numbers.reshape(3, 2, order='F')
>>> reshaped_numbers
array([[1, 4],
[2, 5],
[3, 6]])

The original array had 2 rows and 3 columns. By reshaping it to a 3x2 array with 'F' order, the elements are arranged in column-major order.

Explore the order Parameter

The order parameter accepts different values to control how the data is rearranged. You can explore these values to understand how they affect the reshaping process.

Reduce a Three-Dimensional Color Image to Two Dimensions

You can also use reshape() to reduce the number of dimensions in a three-dimensional color image. This can be useful when you want to flatten the image or perform operations that require two dimensions only.

Here’s an example:

Python

>>> import numpy as np
>>> image = np.array([
... [[255, 0, 0], [0, 255, 0], [0, 0, 255]],
... [[0, 0, 255], [0, 255, 0], [255, 0, 0]]
... ])
>>> reshaped_image = image.reshape(2, 9)
>>> reshaped_image
array([[255, 0, 0, 0, 255, 0, 0, 0, 255],
[ 0, 0, 255, 0, 255, 0, 255, 0, 0]])

The original image had dimensions of (2, 3, 3), representing 2 rows, 3 columns, and 3 color channels (red, green, and blue). By reshaping it to a 2x9 array, the color image is flattened to a two-dimensional representation.

Use -1 as an Argument in NumPy reshape()

Sometimes, you may want to reshape an array while keeping the number of elements unchanged. In such cases, you can use a wildcard value of -1 for one of the dimensions in reshape(). This allows NumPy to automatically determine the correct size for that dimension.

Here’s an example:

Python

>>> import numpy as np
>>> numbers = np.array([1, 2, 3, 4, 5, 6])
>>> reshaped_numbers = numbers.reshape(2, -1)
>>> reshaped_numbers
array([[1, 2, 3],
[4, 5, 6]])

In this example, the original array had 6 elements. By specifying 2 for the first dimension and -1 for the second dimension, NumPy automatically determines that the second dimension should have a size of 3 to accommodate all the elements.

Conclusion

In this tutorial, you learned how to use NumPy’s reshape() function to change the shape of an array. You learned how to reshape an array without changing its number of dimensions, how to add and remove dimensions, and how to control how the data is rearranged. You also learned how to use the wildcard value -1 to automatically determine the correct size of a dimension.

With this knowledge, you can now manipulate the shape of NumPy arrays to meet the needs of your applications. Reshaping arrays can be particularly useful in tasks such as data preprocessing and feature engineering for machine learning.

To further enhance your understanding, you can explore more features and functions provided by NumPy. Additionally, you can apply the knowledge gained in this tutorial to real-world problems and projects to deepen your understanding and improve your skills in NumPy programming.