How to reshape a 1D array into 2D and print Strides using NumPy?
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.
Python-Numpy Code Editor:
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