in

NumPy reshape(): How to Reshape NumPy Arrays in Python

NumPy is a fundamental Python package for scientific computing and data analysis. It provides powerful array structures to work with numerical data in Python.

One of the most useful array operations in NumPy is reshape(). It allows you to change the shape of an array without modifying its data.

In this comprehensive guide, you‘ll learn:

  • What array reshaping is in NumPy and why it‘s useful
  • The syntax for the NumPy reshape() function
  • How to reshape 1D and 2D arrays to different dimensions
  • Techniques to avoid errors during reshaping
  • How to flatten arrays using reshape()
  • The difference between views and copies of arrays

By the end of this tutorial, you‘ll be confident using NumPy reshape() for your data analysis and modeling tasks.

What is Array Reshaping in NumPy?

The NumPy library provides n-dimensional array structures called ndarray. These arrays are the building blocks of most data operations in NumPy.

When you first create arrays in NumPy, you need to define the shape or dimensions upfront. For example:

import numpy as np

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

# Output: (6,) 

This creates a 1D array with 6 elements.

However, later in your data workflow, you may want to transform this array into an array of different dimensions.

For instance, you may need a 2D array with 3 rows and 2 columns, like this:

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

This transformation of an array from one shape to another is called reshaping.

Array reshaping is very common while analyzing data in NumPy. You may create arrays of a certain shape based on your initial assumptions. But later, you may need to restructure the same data in an array of a different shape for further processing.

This is where the reshape() function comes into play. It allows you to reshape an array without changing the position of elements.

Syntax of NumPy reshape()

Here is the standard syntax for the NumPy reshape() function:

np.reshape(arr, newshape, order=‘C‘)

Where:

  • arr is the array to be reshaped
  • newshape is the new shape you want for the array
  • order is the index ordering in the reshaped array

Let‘s understand what each of these parameters means:

  • arr can be any valid numpy ndarray. This array will be reshaped to the new shape.
  • newshape defines the new shape you want. It can be a tuple of ints or a single int.
    • If newshape is an int, the result is a 1D array with that many elements.
    • If it‘s a tuple of ints, you define the exact shape you want.
  • order refers to how elements should be read in the reshaped array.
    • ‘C‘ means read in row-major (C-style) order. This is default.
    • ‘F‘ means read in column-major (Fortran-style) order.
    • ‘A‘ means read in order based on array‘s memory layout.

What does reshape() return?

It returns a reshaped view of the original array if possible. Else, it returns a copy of the array.

The difference between views and copies is important:

  • View: Reshaped array looking at same data as original array. Changes to view affect original array.
  • Copy: Separate replica of original data. Changes don‘t affect original array.

NumPy tries to return a view wherever possible to avoid extra memory usage. But for certain reshape operations, it has to make a copy.

Now let‘s look at how to use reshape() for some common examples.

Reshape a 1D Array to 2D Arrays

Let‘s start by generating a 1D array and then reshaping it to different 2D shapes.

Example 1: Reshaping 1D Array to 4 x 3

First, generate an array of 12 elements using np.arange():

import numpy as np

arr1 = np.arange(1, 13) 

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

Now reshape it into a 2D array of shape (4, 3):

arr2 = arr1.reshape(4, 3) 

print(arr2)
"""
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
"""

We reshaped the 12 elements into a 4 x 3 array successfully!

Instead of passing arr1 to np.reshape(), we can also call .reshape() directly on arr1. Both approaches work.

To check if we got a view or copy, use the base attribute:

print(arr2.base)
# [1 2 3 4 5 6 7 8 9 10 11 12] 

# Returns original array, so it‘s a view

Example 2: Reshaping 1D Array to 12 x 1

Let‘s now try reshaping the array to 12 x 1:

arr3 = arr1.reshape(12, 1)

print(arr3)
"""
[[ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]  
 [ 7]
 [ 8]
 [ 9] 
[10]
[11]
[12]]
""" 

We reshaped the 1D array into a 12 x 1 vertical shape.

Verify that this is also a view:

print(arr3.base) 

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

Example 3: Reshaping 1D Array to 2 x 6

Finally, let‘s reshape the array to 2 x 6:

arr4 = arr1.reshape(2, 6)

print(arr4)
"""
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]
"""

So we‘ve successfully reshaped the 1D array into different 2D shapes, all views of the original data.

Reshape a 1D Array to 3D Arrays

Reshaping to 3D arrays follows the same process.

Let‘s reshape the 1D array from previous section to a 3D shape of (1, 4, 3):

arr3d = arr1.reshape(1, 4, 3) 

print(arr3d)
"""
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]
  [10 11 12]]]  
"""

We now have a 3D array with the same 12 elements.

The key is ensuring the overall number of elements matches in the new shape.

Avoiding Errors during Array Reshaping

What happens if we try to reshape into an invalid new shape?

Let‘s try reshaping arr1 into a 4 x 4 array:

arr2d = arr1.reshape(4, 4)

This gives a ValueError since arr1 has 12 elements while 4 x 4 requires 16 elements:

ValueError: cannot reshape array of size 12 into shape (4,4)

To avoid such errors, we can use -1 in newshape to automatically calculate the dimension that maintains the total number of elements:

For example:

arr1 = np.arange(1, 25) # 1D array with 24 elements

arr_reshaped = arr1.reshape(3, 4, -1) 

print(arr_reshaped.shape)
# (3, 4, 2)

By using -1 in newshape, NumPy infers the 3rd dimension as 2 to maintain 24 elements.

This is very useful when you know the dimension upfront for all axes except one.

Flattening Arrays using Reshape

Another common use of reshape() is to flatten arrays, i.e. convert N-D arrays to 1D arrays.

For flattening, we can use -1 without specifying any other dimensions:

arr2d = np.random.rand(3, 5) # Random 2D array 

flattened = arr2d.reshape(-1) # Flatten

print(flattened.shape)
# (15,) 

This is useful for vectorizing array operations and machine learning workflows.

Let‘s look at a simple image flattening example:

img_arr = np.random.randint(0, 255, (3, 3)) # Random 3x3 image

print(img_arr.shape)
# (3, 3) 

flat_img = img_arr.reshape(-1) 

print(flat_img.shape)
# (9,) Flattened array

So reshape(-1) provides an easy way to flatten arrays to 1D.

Summary of NumPy Reshape()

In this detailed guide you learned:

  • np.reshape() reshapes arrays to new shapes without changing data.
  • Use newshape argument to define new shape as tuple of ints.
  • Set newshape as -1 to flatten arrays.
  • Reshape() returns view of array if possible, else copy.
  • Check .base attribute to verify view vs copy.
  • Use -1 in newshape to avoid reshape errors.
  • Flattening using reshape(-1) is useful for ML.

NumPy‘s powerful reshape() gives you flexibility to transform arrays for your data analysis workflows. Use this guide as a NumPy cheat sheet for array reshaping operations.

Check out Geekflare‘s other NumPy tutorials to level up your Python data analysis skills!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.