w3resource

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


6. 1D to 2D to Different Shape Transformation

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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to reshape a 1D array of 16 elements into (8, 2) and then back to (4, 4), printing shape and strides at each step.
  • Write a NumPy program to verify that reshaping a 1D array into different 2D shapes retains the same data pointer.
  • Write a NumPy program to perform sequential reshaping on a 1D array and display how the strides change with each transformation.
  • Write a NumPy program to reshape a 1D array into a 2D array, modify one shape, and check if the memory ordering remains consistent.

Go to:


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

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.