Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Array Reshape

Reshaping in NumPy refers to changing the shape (dimensions) of an array without changing its data. This means that the total number of elements in the array remains the same after reshaping.


The reshape() function in NumPy allows you to do this. It returns a new array with the specified shape while maintaining the original data. Here's how it works:


import numpy as np
# Create a 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshape the array into a 2D array with 3 rows and 2 columns
reshaped_arr = arr.reshape(3, 2)
print("Original array:")
print(arr)
print("Reshaped array:")
print(reshaped_arr)


Output

Original array:
[1 2 3 4 5 6]
Reshaped array:
[[1 2]
[3 4]
[5 6]]

In this example, we start with a 1-dimensional array arr with 6 elements. We then use reshape(3, 2) to transform it into a 2-dimensional array with 3 rows and 2 columns. The resulting array reshaped_arr has the same data as arr, but it's arranged in a different shape.


A few important things to note about reshaping:
Compatibility: The total number of elements in the original array must match the total number of elements in the reshaped array. Otherwise, NumPy will raise a ValueError.
Order:By default, NumPy uses row-major order (C-order) to reshape arrays. This means that elements are arranged row by row. You can also specify the order explicitly using the order parameter.
Views: Reshaping creates a new view of the original array with a different shape. It doesn't create a copy of the data, so modifying the reshaped array will also affect the original array.
Special Values: You can use -1 as one of the dimensions in reshape(), and NumPy will automatically calculate the correct size for that dimension based on the total number of elements in the array. This is useful for reshaping arrays where one dimension's size is unknown.





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java