Open In App

Numpy Reshape 2D To 3D Array

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

NumPy is a powerful library in Python used for numerical operations and data analysis. Reshaping arrays is a common operation in NumPy, and it allows you to change the dimensions of an array without changing its data. In this article, we’ll discuss how to reshape a 2D NumPy array into a 3D array.

Understanding 2D and 3D Arrays

  • A 2D array is a collection of data points arranged in rows and columns, forming a matrix. It can be visualized as a spreadsheet or a grid.
  • A 3D array is an extension of a 2D array, where an additional dimension is added, typically representing depth or volume. It can be visualized as a stack of 2D arrays.

Reshaping a 2D Array to 3D using reshape() method

To reshape a 2D NumPy array into a 3D array, you can use the reshape() method. The reshape() method takes two arguments:

  • The desired shape of the 3D array as a tuple
  • The original 2D array

Example 1

Python3




import numpy as np
# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Original 2D array:")
print(array_2d)
 
# Reshape the 2D array into a 3D array with shape (3, 3, 1)
array_3d = array_2d.reshape((3, 3, 1))
print("\nReshaped 3D array:")
print(array_3d)


Output:

Original 2D array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Reshaped 3D array:
[[[1]
[2]
[3]]
[[4]
[5]
[6]]
[[7]
[8]
[9]]]

In this example, the original 2D array has three rows and three columns. We reshaped it into a 3D array with the shape (3, 3, 1). The resulting 3D array has three 2D slices, each with a shape of (3, 3). The additional dimension (the third dimension) has a size of 1, indicating that each 2D slice has a depth of 1.

Example 2

Python3




import numpy as np
 
# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
 
# Reshape the 2D array into a 3D array with shape (2, 2, 3)
array_3d = array_2d.reshape((2, 2, 3))
 
print("Original 2D array:")
print(array_2d)
print("\nReshaped 3D array:")
print(array_3d)


Output:

Original 2D array:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Reshaped 3D array:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]

The original 2D array is reshaped into a 3D array with a shape of (2, 2, 3).

Conclusion

Reshaping arrays is a fundamental operation in NumPy, and it allows you to manipulate data in various ways. Reshaping a 2D array into a 3D array can be useful for representing data with an additional dimension, such as depth or volume. Additionally, reshaping a flattened array into a 3D array can help organize data into a structured format. By understanding how to reshape arrays, you can effectively work with multidimensional data in NumPy.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads