Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
numpy.ravel() in Python
Next article icon

numpy.reshape() in Python

Last Updated : 13 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, numpy.reshape() function is used to give a new shape to an existing NumPy array without changing its data. It is important for manipulating array structures in Python.

Let’s understand with an example:

Python
import numpy as np  # Creating a 1D NumPy array  arr = np.array([1, 2, 3, 4, 5, 6])  # Reshaping the 1D array into a 2D array with 2 rows and 3 columns reshaped_arr = np.reshape(arr, (2, 3)) print(reshaped_arr) 

Output
[[1 2 3]  [4 5 6]] 

Explanation:

  • array arr is reshaped into a 2×3 matrix, where 2 is number of rows and 3 is number of columns.
  • Each element from the original array is rearranged into the new shape while maintaining the order.

Table of Content

  • Syntax of numpy.reshape() :
  • Using -1 to infer a dimension
  • Reshaping with column-major order

Syntax of numpy.reshape() :

numpy.reshape(array, shape, order = ‘C’)

Parameters : 

  • array : [array_like]Input array
  • shape : [int or tuples of int] e.g. The desired shape of the array. If one dimension is -1, the value is inferred from the length of the array and the remaining dimensions.
  • order : [C-contiguous, F-contiguous, A-contiguous; optional]
    • 'C' (default): Row-major order.
    • 'F': Column-major order.
    • 'A': Fortran-like index order if the array is Fortran-contiguous; otherwise, C-like order.
    • 'K': Keeps the array’s order as close to its original as possible.

Return Type: 

  • Array which is reshaped without changing the data.

Using -1 to infer a dimension

It allows to automatically calculate the dimension that is unspecified as long as the total size of the array remains consistent.

Python
import numpy as np  # Creating a 1D NumPy array  arr = np.array([1, 2, 3, 4, 5, 6])  # Reshaping the array into a 2D array # '-1' allows to calculate the number of rows based on the total number of elements reshaped_arr = np.reshape(arr, (-1, 2))   print(reshaped_arr) 

Output
[[1 2]  [3 4]  [5 6]] 

Explanation:

  • -1 allows NumPy to automatically calculate the number of rows needed based on the total size and the other given dimension.
  • resulting array has 3 rows and 2 columns, as NumPy calculates the required number of rows.

Reshaping with column-major order

We can specify the order in which the elements are read from the original array and placed into the new shape.

Python
import numpy as np  # Creating a 1D NumPy array  arr = np.array([1, 2, 3, 4, 5, 6])  # Reshaping the array into a 2D array with 2 rows and 3 columns reshaped_arr = np.reshape(arr, (2, 3), order='F') print(reshaped_arr) 

Output
[[1 3 5]  [2 4 6]] 

Explanation:

  • order=’F’ argument reshapes the array in a column-major (Fortran-style) order, meaning the elements are filled by columns instead of rows.
  • The result is a 2×3 matrix where the data is arranged column-wise.


Next Article
numpy.ravel() in Python
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Python
  • Python numpy-arrayManipulation
  • Python-numpy
Practice Tags :
  • python

Similar Reads

  • numpy.repeat() in Python
    The numpy.repeat() function repeats elements of the array - arr. Syntax : numpy.repeat(arr, repetitions, axis = None) Parameters : array : [array_like]Input array. repetitions : No. of repetitions of each array elements along the given axis. axis : Axis along which we want to repeat values. By defau
    2 min read
  • Python | Numpy matrix.reshape()
    With the help of Numpy matrix.reshape() method, we are able to reshape the shape of the given matrix. Remember all elements should be covered after reshaping the given matrix. Syntax : matrix.reshape(shape) Return: new reshaped matrix Example #1 : In the given example we are able to reshape the give
    1 min read
  • numpy.ravel() in Python
    The numpy.ravel() functions returns contiguous flattened array(1D array with all the input-array elements and with the same type as it). A copy is made only if needed. Syntax : numpy.ravel(array, order = 'C')Parameters : array : [array_like]Input array. order : [C-contiguous, F-contiguous, A-contigu
    3 min read
  • numpy.take() in Python
    The numpy.take() function returns elements from array along the mentioned axis and indices. Syntax: numpy.take(array, indices, axis = None, out = None, mode ='raise') Parameters : array : array_like, input array indices : index of the values to be fetched axis : [int, optional] axis over which we ne
    2 min read
  • numpy.unwrap() in Python
    numpy.unwrap(p, discount=3.141592653589793, axis=-1) function helps user to unwrap a given array by changing deltas to values of 2*pi complement. It unwraps radian phase p by changing absolute jumps greater than discount to their 2*pi complement along the given axis. Result is an unwrapped array. Pa
    2 min read
  • numpy.stack() in Python
    NumPy is a famous Python library used for working with arrays. One of the important functions of this library is stack(). Important points:stack() is used for joining multiple NumPy arrays. Unlike, concatenate(), it joins arrays along a new axis. It returns a NumPy array.to join 2 arrays, they must
    5 min read
  • numpy.zeros() in Python
    numpy.zeros() function creates a new array of specified shapes and types, filled with zeros. It is beneficial when you need a placeholder array to initialize variables or store intermediate results. We can create 1D array using numpy.zeros(). Let's understand with the help of an example: [GFGTABS] P
    2 min read
  • numpy.vstack() in python
    numpy.vstack() is a function in NumPy used to stack arrays vertically (row-wise). It takes a sequence of arrays as input and returns a single array by stacking them along the vertical axis (axis 0). Example: Vertical Stacking of 1D Arrays Using numpy.vstack() [GFGTABS] Python import numpy as geek a
    2 min read
  • numpy.roll() in Python
    The numpy.roll() function rolls array elements along the specified axis. Basically what happens is that elements of the input array are being shifted. If an element is being rolled first to the last position, it is rolled back to the first position. Syntax : numpy.roll(array, shift, axis = None) Par
    2 min read
  • numpy.tile() in Python
    The numpy.tile() function constructs a new array by repeating array - 'arr', the number of times we want to repeat as per repetitions. The resulted array will have dimensions max(arr.ndim, repetitions) where, repetitions is the length of repetitions. If arr.ndim > repetitions, reps is promoted to
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences