w3resource

NumPy: Create a new shape to an array without changing its data


Reshape Array (Keep Data)

Write a NumPy program to create another shape from an array without changing its data.

Pictorial Presentation:

Python NumPy: Create a new shape to an array without changing its data

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 1D NumPy array with six elements
x = np.array([1, 2, 3, 4, 5, 6])

# Reshaping the array 'x' into a 3x2 matrix and assigning it to variable 'y'
y = np.reshape(x, (3, 2))
print("Reshape 3x2:")  # Printing the description for the reshaped 3x2 array
print(y)  # Displaying the reshaped 3x2 array

# Reshaping the array 'x' into a 2x3 matrix and assigning it to variable 'z'
z = np.reshape(x, (2, 3))
print("Reshape 2x3:")  # Printing the description for the reshaped 2x3 array
print(z)  # Displaying the reshaped 2x3 array 

Sample Output:

Reshape 3x2:                                                           
[[1 2]                                                                 
 [3 4]                                                                 
 [5 6]]                                                                
Reshape 2x3:                                                           
[[1 2 3]                                                               
 [4 5 6]] 

Explanation:

In the above code -

x = np.array([1, 2, 3, 4, 5, 6]): This line creates a one-dimensional NumPy array ‘x’ with six elements.

y = np.reshape(x,(3,2)): This line reshapes the ‘x’ array into a new two-dimensional array ‘y’ with 3 rows and 2 columns. The elements from ‘x’ are placed row-wise into the new shape.

print(y): This line prints the reshaped ‘y’ array.

z = np.reshape(x,(2,3)): This line reshapes the ‘x’ array into another two-dimensional array ‘z’ with 2 rows and 3 columns. Again, the elements from ‘x’ are placed row-wise into the new shape.

print(z): This line prints the reshaped ‘z’ array.


For more Practice: Solve these Related Problems:

  • Reshape a given array into different dimensions while ensuring that the data remains unchanged.
  • Create a function that reshapes an array and then verifies the integrity of its elements post-transformation.
  • Test reshaping on arrays where one dimension is inferred using -1 and check for correctness.
  • Compare the flattened version of the original array with the reshaped array to ensure identical ordering.

Go to:


PREV : Create 2D Array & Print Shape/Type
NEXT : Change Array Data Type


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.