SoFunction
Updated on 2025-04-14

Detailed explanation of the use of reshape in Python

Use of reshape in Python

In Python,reshapeFunctions are mainly used to adjust the dimensions of arrays or matrices.Especially common in NumPy and Pandas libraries

The following are detailed usage and examples:

1. reshape in NumPy

NumPy'sreshapeIt is the core tool for adjusting array dimensions and is suitable for scientific computing and multidimensional data processing.

Basic syntax

(array, new_shape, order='C')

Or call the array object directlyreshapemethod:

(new_shape)

Parameter description

​**new_shape: Target shape (e.g.(row, column)), can be an integer or a tuple.

  • Key Rule**: The total number of elements in the new shape must be consistent with the original array (for example, the original array has 6 elements, which can be changed to(2,3), but cannot be changed to(3,3))。

​**order**: Optional parameters, control the order of element filling:

  • 'C'(Default): Fill by row-first (C-style).
  • 'F': Fill in column-first (Fortran style).

Sample code

  • Example 1: One-dimensional to two-dimensional
import numpy as np

arr = ([1, 2, 3, 4, 5, 6])
reshaped = ((2, 3))  # Change to 2 rows and 3 columnsprint(reshaped)
#Output:# [[1 2 3]
#  [4 5 6]]
  • Example 2: Multidimensional array adjustment
matrix = ([[1, 2], [3, 4], [5, 6]])
# Change to 2 rows and 3 columns (the total number of elements must be 6)new_matrix = ((2, 3))  
print(new_matrix)
#Output:# [[1 2 3]
#  [4 5 6]]
  • Example 3: Automatically infer dimensions (using-1

pass-1Automatically calculate the size of a certain dimension:

arr = ([1, 2, 3, 4, 5, 6])
# Automatically calculate the number of rows (total number of elements = 6 → number of rows = 6/3 = 2)reshaped = ((-1, 3))  
print(reshaped)
#Output:# [[1 2 3]
#  [4 5 6]]
  • Example 4: Adjust the dimension order (orderparameter)
arr = ([1, 2, 3, 4, 5, 6])
# Populate by column firstfortran_arr = ((2, 3), order='F')  
print(fortran_arr)
#Output:# [[1 3 5]
#  [2 4 6]]

2. Reshape in Pandas

Pandas mainly implements data reshaping through the following methods:

  • ​**stack() / unstack()**: Row and column conversion.
  • ​**pivot() / melt()**: Conversion of wide tables and long tables.

Examples: stack and unstack

import pandas as pd

# Create a DataFramedf = ({
    "A": [1, 2, 3],
    "B": [4, 5, 6]
}, index=["X", "Y", "Z"])

# Stack columns into rows (generate multi-level indexes)stacked = ()
print(stacked)
#Output:# X  A    1
#    B    4
# Y  A    2
#    B    5
# Z  A    3
#    B    6

# Restore the original shapeunstacked = ()
print(unstacked)

3. Things to note

The total number of elements must be consistent: Otherwise it will be thrownValueError

Is it a view or a copy?

  • NumPy'sreshapeThe default return to the view (modifying the view will affect the original array).
  • If the view cannot be generated (such as memory discontinuous), a copy is returned.

Avoid confusionreshape andresize

  • reshapeDon't change the original array, return the new shape array.
  • resizeModify the shape of the original array directly (may cause data truncation or fill).

4. Practical application scenarios

  • Image processing: Convert a one-dimensional pixel array to three-dimensional (height, width, number of channels).
  • Machine Learning: Adjust the shape of the input data to match the model requirements (such as(Number of samples,)Change to(Number of samples, 1))。
  • Data cleaning: Convert wide table to long table (Pandas'smelt)。

5. Common Errors

# Error example: Total number of elements does not matcharr = ([1, 2, 3])
try:
    ((2, 2))  # 3 element cannot fill the position of 2x2=4except ValueError as e:
    print(e)  # Output:cannot reshape array of size 3 into shape (2,2)

passreshape, you can flexibly process data dimensions and adapt to the needs of different algorithms and scenarios. Select the corresponding method of NumPy (multi-dimensional array) or Pandas (table data) according to the task.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.