w3resource

How to reshape a 1D NumPy array to multiple dimensions?

NumPy: Memory Layout Exercise-6 with Solution

Write a NumPy program that creates a 1D array of 16 elements, reshape it to (4, 4), then change its shape to (2, 8) without changing the underlying data.

Sample Solution:

Python Code:

import numpy as np

# Create a 1D array of 16 elements
array_1d = np.arange(1, 17)

# Reshape the 1D array to a 2D array of shape (4, 4)
array_2d = array_1d.reshape(4, 4)

# Change the shape of the array to (2, 8) without changing the underlying data
reshaped_array = array_2d.reshape(2, 8)

# Print the reshaped array
print(reshaped_array)

Output:

[[ 1  2  3  4  5  6  7  8]
 [ 9 10 11 12 13 14 15 16]]

Explanation:

  • Import NumPy library: We start by importing the NumPy library to handle array operations.
  • Create a 1D array: We create a 1D array array_1d with 16 elements using np.arange(1, 17).
  • Reshape to (4, 4): We reshape the 1D array to a 2D array array_2d of shape (4, 4) using reshape().
  • Change shape to (2, 8): We further reshape array_2d to a new shape (2, 8) without changing the underlying data, resulting in reshaped_array.
  • Print the result: Finally, we print the reshaped_array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to create and change Strides of a 2D NumPy array?
Next: How to reshape a 2D NumPy array to a 3D array?

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-numpy-array-to-multiple-dimensions.php