In NumPy, the reshape
function is used to change the shape of an array without changing its data. Here are some examples of using reshape
with different scenarios:
Example 1: Basic Reshape
import numpy as np
# Create a 1D array
arr_1d = np.array([1, 2, 3, 4, 5, 6])
# Reshape to a 2D array with 2 rows and 3 columns
arr_2d = arr_1d.reshape((2, 3))
print("Original 1D array:")
print(arr_1d)
print("\nReshaped 2D array:")
print(arr_2d)
Output:
Original 1D array:
[1 2 3 4 5 6]
Reshaped 2D array:
[[1 2 3]
[4 5 6]]
Example 2: Reshape with -1
Using -1
as one of the dimensions allows NumPy to automatically calculate the size of that dimension based on the size of the original array.
import numpy as np
# Create a 1D array with 12 elements
arr_1d = np.arange(1, 13)
# Reshape to a 2D array with 3 rows and an automatically calculated number of columns
arr_2d = arr_1d.reshape((3, -1))
print("Original 1D array:")
print(arr_1d)
print("\nReshaped 2D array:")
print(arr_2d)
Output:
Original 1D array:
[ 1 2 3 4 5 6 7 8 9 10 11 12]
Reshaped 2D array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Example 3: Reshape for 3D Array
import numpy as np
# Create a 1D array with 24 elements
arr_1d = np.arange(1, 25)
# Reshape to a 3D array with 2 planes, 3 rows, and 4 columns
arr_3d = arr_1d.reshape((2, 3, 4))
print("Original 1D array:")
print(arr_1d)
print("\nReshaped 3D array:")
print(arr_3d)
Output:
Original 1D array:
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
Reshaped 3D array:
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
These examples showcase different use cases for reshaping arrays using the reshape
function in NumPy. Adjust the dimensions and content of the arrays based on your specific requirements.