NumPy’s reshape

NumPy is a powerful library for working with multi-dimensional arrays in Python. One useful function it provides is numpy.reshape, which allows you to reshape an array to a new shape.

Here is an example of using numpy.reshape to reshape a 1-dimensional array of integers into a 3×3 2-dimensional array:

import numpy as np

# Our 1-dimensional array
data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])

# Reshape the array to a 3x3 2-dimensional array
data = np.reshape(data, (3, 3))

print(data)

The output will be:

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

You can also use the -1 placeholder to automatically infer the size of one of the dimensions. For example, this code will also reshape the data array into a 3×3 2-dimensional array:

import numpy as np

# Our 1-dimensional array
data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])

# Reshape the array to a 3x3 2-dimensional array
data = np.reshape(data, (3, -1))

print(data)

The output will be the same as before:

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