w3resource

How to reshape a 1D array into 2D and print Strides using NumPy?

NumPy: Memory Layout Exercise-2 with Solution

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/reshape-a-1d-array-into-2d-and-print-strides-using-numpy.php