.reshape()
The .reshape()
method rearranges the data in an ndarray
into a new shape. The new shape must be compatible with the old one, though an index of -1
can be used to infer one dimension.
Syntax
ndarray.reshape(newshape)
Where newshape
can be an integer or a tuple
representing the size of the new array. If a dimension is -1
, that dimension will be inferred from the size of the original array.
Unlike the built-in NumPy function .reshape()
, dimensions for this method can also be passed as separate arguments: i.e. array.reshape(2,3)
is the same as array.reshape((2,3))
.
If possible, the ndarray
returned will be a view of the original ndarray
‘s data.
Example
The following example creates an ndarray
then uses .reshape()
to change its dimensions.
import numpy as npnd1 = np.array([[1,2,3],[4,5,6]])print(nd1)print(nd1.reshape(3,2))print(nd1.reshape((-1,1)))
This produces the following output:
[[1 2 3][4 5 6]][[1 2][3 4][5 6]][[1][2][3][4][5][6]]
Codebyte Example
Run the following codebyte example to understand the usage of the .reshape()
method:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours