Share on:

December 29, 2019

1. Introduction
2. NumPy Arrays
2.1 What’s A NumPy Array
2.2 Creating NumPy Arrays
2.3 Indexing And Modifying 1-D Arrays
2.4 Indexing And Modifying Multidimensional Arrays
2.5 Basic Math
3. Intermediate Array Stuff
3.2 newaxis
3.3 reshape
3.4 boolean indexing
3.5 nan
3.6 infinity
3.7 random
4. Common Operations
4.1 where
4.2 Math Funcs
4.3 all and any
4.4 concatenate
4.5 Stacking
4.6 Sorting
4.7 unique
5. Challenges

This video covers NumPy’s reshape() function for restructuring the shape of a NumPy array.

# Code

import numpy as np

# Suppose we have the following 1d array with 8 elements
foo = np.arange(start = 1, stop = 9)  # [1, 2, 3, 4, 5, 6, 7, 8]

# reshape into a 2x4 array using either the .reshape method of the array object, or the free function np.reshape()
bar = foo.reshape((2,4))
bar = np.reshape(a = foo, newshape = (2,4))

# slightly different interfaces
foo.reshape(2,4)  # allowed
foo.reshape(newshape = (2,4))  # error

## reshape bar from a 2x4 array to a 4x2 array
# C-style order reorders the last axis first
bar.reshape((4,2), order = 'C')

# Fortran-style order reorders the first axis first
bar.reshape((4,2), order = 'F')

# matrix transpose of bar
bar.T

# reshape foo into higher dimensions, like a 2x2x2 array
bar.reshape((2,2,2))

# reshape foo into 2x2x3 array
bar.reshape((2,2,3)) # error

# use -1 for exactly one of the newshape dimensions and numpy will calculate it for you
bar.reshape((-1, 2))

# Transcript

You’ll often find yourself needing to reshape arrays. numpy makes this easy with the reshape() function. Suppose we have the following 1d array with 8 elements called foo.
We can reshape foo into a 2x4 array using either the .reshape() method of the array object, or the free function np.reshape() These methods implement the same logic, just with slightly different interfaces. With foo.reshape, we can pass in the new dimensions individually instead of as a tuple, but this comes at the expense of not being able to specify the ‘newshape’ keyword. Now let’s reshape bar from a 2x4 array to a 4x2 array. We can do this in two different orders.
First, we’ll call bar.reshape with order equal to ‘C’. This implements C-style order which reorders the last axis first.
Next, we’ll call bar.reshape with order equal to ‘F’. This implements Fortran-style order which reorders the first axis first.

You might also be interested in the matrix transpose of bar, which also happens to be a 4x2 array. You can get that with bar.T or the free function np.transpose(bar).
You can also reshape foo into higher dimensions, like a 2x2x2 array.
However, the newshape you specify must hold the same number of elements as the original array. If it doesn’t, you’ll get an error. If you’re feeling lazy, use -1 for exactly one of the newshape dimensions and numpy will calculate it for you.