Introduction
In NumPy Array Reshape, the reshape() method is used to change the structure of an array without changing its data. For example, you can convert a 1-D array into a 2-D or 3-D array. Reshaping is useful when organizing data for analysis, machine learning, and other data science tasks.
1. What is Reshaping in NumPy?
Reshaping means changing the dimensions of an array while keeping the same elements.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
new_arr = arr.reshape(2, 3)
print(new_arr)
Output:
[[10 20 30]
[40 50 60]]
Explanation:
- The original array contains 6 elements.
reshape(2, 3)converts it into 2 rows and 3 columns.- All original values remain unchanged.
2. Convert a 1-D Array into a 2-D Array
You can use reshape() to convert a one-dimensional array into a two-dimensional array.
Example:
import numpy as np
marks = np.array([75, 80, 85, 90, 95, 88])
new_marks = marks.reshape(3, 2)
print(new_marks)
Output:
[[75 80]
[85 90]
[95 88]]
Explanation:
The original array has 6 elements. Using reshape(3, 2) arranges these elements into 3 rows and 2 columns.
3. Convert a 1-D Array into a 3-D Array
You can also convert a one-dimensional array into a three-dimensional array by providing three dimensions in reshape().
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
new_arr = arr.reshape(2, 2, 3)
print(new_arr)
Output:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Explanation:
2represents the number of groups.2represents the number of rows in each group.3represents the number of columns in each row.
The array contains 12 elements, arranged into 2 groups, each with 2 rows and 3 columns.
4. Convert a 2-D Array into a 1-D Array
You can use reshape() to convert a two-dimensional array into a one-dimensional array.
Example:
import numpy as np
arr = np.array([
[10, 20, 30],
[40, 50, 60]
])
new_arr = arr.reshape(6)
print(new_arr)
Output:
[10 20 30 40 50 60]
Explanation:
The original array has 2 rows and 3 columns. Using reshape(6) converts it into a one-dimensional array containing all 6 elements.
5. Use -1 in NumPy Reshape
NumPy allows you to use -1 in reshape() when you want NumPy to automatically calculate one dimension.
You do not need to calculate that dimension yourself.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
new_arr = arr.reshape(2, -1)
print(new_arr)
Output:
[[10 20 30]
[40 50 60]]
Explanation:
- We provide 2 rows.
- We use
-1for the number of columns. - NumPy automatically calculates 3 columns.
You can also use reshape(-1, 2) to let NumPy calculate the number of rows.
6. Check Whether Reshaping Returns a View or a Copy
NumPy may return a view or a copy when you reshape an array. When possible, it returns a view that shares the original data. If a view is not possible, NumPy may create a copy.
You can check the base attribute to see whether the reshaped array is based on another array.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
new_arr = arr.reshape(2, 3)
print(new_arr.base is arr)
Output:
True
Explanation:
Here, True indicates that the reshaped array is based on the original array.
Note: Do not assume that every reshape operation always returns a view. It depends on the array’s memory layout and the requested shape.
7. What Happens If the Shape Does Not Match?
The total number of elements must remain the same when reshaping an array.
For example, an array containing 6 elements can be reshaped into (2, 3) or (3, 2), but not (2, 4).
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
new_arr = arr.reshape(2, 4)
print(new_arr)
Output:
ValueError: cannot reshape array of size 6 into shape (2,4)
Explanation:
- The original array contains 6 elements.
- The requested shape
(2, 4)requires 8 elements. - Since the number of elements does not match, NumPy raises a
ValueError.
Student Task
A school stores the marks of 12 students in a one-dimensional array.
import numpy as np
marks = np.array([
75, 80, 85, 90,
65, 70, 95, 88,
78, 82, 89, 92
])
Complete these tasks:
- Convert the array into 3 rows and 4 columns.
- Convert it into 4 rows and 3 columns.
- Convert it into a 3-D array with 2 groups, 2 rows, and 3 columns.
- Convert it back into a 1-D array.
- Use
-1to let NumPy automatically calculate the number of rows.
Final Student Challenge: Company Monthly Sales Records
A company stores sales figures for 12 employees. Each employee has one sales value for each month in a four-month period.
import numpy as np
sales = np.array([
12000, 15000, 18000, 20000,
14000, 16000, 19000, 22000,
11000, 13000, 17000, 21000
])
# Convert into 3 rows and 4 columns
sales_2d = sales.reshape(3, 4)
# Convert into 2 groups, 2 rows and 3 columns
sales_3d = sales.reshape(2, 2, 3)
# Automatically calculate the number of rows
sales_auto = sales.reshape(-1, 3)
print("2-D Sales Array:")
print(sales_2d)
print("\n3-D Sales Array:")
print(sales_3d)
print("\nAutomatically Reshaped Array:")
print(sales_auto)
Expected Output:
2-D Sales Array:
[[12000 15000 18000 20000]
[14000 16000 19000 22000]
[11000 13000 17000 21000]]
3-D Sales Array:
[[[12000 15000 18000]
[20000 14000 16000]]
[[19000 22000 11000]
[13000 17000 21000]]]
Automatically Reshaped Array:
[[12000 15000 18000]
[20000 14000 16000]
[19000 22000 11000]
[13000 17000 21000]]
Your Challenge:
- Create an array containing 24 employee sales values.
- Reshape it into 6 rows and 4 columns.
- Convert it into a 3-D array with 2 groups, 3 rows, and 4 columns.
- Use
-1to reshape it into 3 columns. - Try an invalid shape and observe the error.
Key Takeaways
reshape()in NumPy changes the dimensions of a NumPy array.- The total number of elements must remain the same.
- A 1-D array can be converted into 2-D or 3-D arrays.
- Use
-1when you want NumPy to calculate one dimension automatically. - Reshaping may return a view or a copy depending on the array’s memory layout.
- An invalid shape raises a
ValueError.
Frequently Asked Questions (FAQs)
1. What is NumPy Array Reshape in Python?
NumPy Array Reshape is used to change the shape of an existing array by rearranging its elements into a different number of rows and columns without changing the original data.
2. What is the NumPy reshape() method?
The NumPy reshape() method is used to change the dimensions of an array. It allows you to convert a 1D array into a 2D array or arrange elements into different dimensions, provided the total number of elements remains the same.
3. How do you use reshape() in NumPy?
You can use the reshape() method by specifying the desired number of rows and columns.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
new_arr = arr.reshape(2, 3)
print(new_arr)
Output:
[[10 20 30]
[40 50 60]]
4. How do you convert a NumPy 1D Array to a 2D Array?
You can convert a NumPy 1D Array to a 2D Array using the reshape() method. For example, arr.reshape(2, 3) converts six elements into two rows and three columns.
5. What are the different NumPy reshape examples?
NumPy reshape examples include converting a 1D array into a 2D array, changing a 2D array into another shape, and converting a 1D array into a 3D array using the reshape() method.
6. Can we reshape a NumPy Array without changing its data?
Yes, you can reshape a NumPy Array without changing its elements. The reshape() method only changes how the elements are arranged in different dimensions.
7. What does -1 mean in the NumPy reshape() method?
In NumPy, -1 tells the reshape() method to automatically calculate the required size of that dimension based on the total number of elements.
Example: arr.reshape(2, -1) automatically calculates the number of columns when two rows are specified.
8. What happens if the new shape does not match the total number of elements?
If the requested shape requires a different number of elements than the original array contains, NumPy raises a ValueError. The total number of elements must remain the same when using the reshape() method.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
