How to reshape a 1D array into 2D and print Strides using NumPy?
2. 1D to 2D Reshape Strides
Write a NumPy program that reshapes a 1D array of 12 elements into a 2D array of shape (3, 4) and print its strides.
Sample Solution:
Python Code:
import numpy as np
# Create a 1D array of 12 elements
a = np.arange(12)
# Reshape the array into a 2D array of shape (3, 4)
reshaped_a = a.reshape((3, 4))
# Print the strides of the reshaped array
print("Strides of the reshaped array:", reshaped_a.strides)
Output:
Strides of the reshaped array: (16, 4)
Explanation:
- Import NumPy: Import the NumPy library to handle array operations.
- Create 1D array a: Define a 1D array a with 12 elements using np.arange(12).
- Reshape the array: Use the reshape() method to convert the 1D array into a 2D array of shape (3, 4).
- Print Strides: Print the strides of the reshaped array using the strides attribute.
For more Practice: Solve these Related Problems:
- Write a NumPy program to reshape a 1D array of 12 elements into a (4, 3) array and print its strides, then compare with the (3, 4) shape.
- Write a NumPy program to reshape a 1D array into a 2D array using Fortran order and display the resulting strides.
- Write a NumPy program to perform multiple reshaping operations on a 1D array and print the strides after each reshape.
- Write a NumPy program to verify that reshaping a 1D array into different 2D shapes preserves the underlying data pointer by comparing strides.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: How to create a 3D array and print its strides using NumPy?
Next: How to create and flatten a 2D NumPy array using ravel()?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics