w3resource

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

NumPy: Array Object Exercise-38 with Solution

Write a NumPy program to create a new shape to 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:

import numpy as np
x = np.array([1, 2, 3, 4, 5, 6])
y = np.reshape(x,(3,2))
print("Reshape 3x2:")
print(y)
z = np.reshape(x,(2,3))
print("Reshape 2x3:")
print(z)

Sample Output:

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

Python Code Editor:

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

Previous: Write a NumPy program to create a 2-dimensional array of size 2 x 3 (composed of 4-byte integer elements), also print the shape, type and data type of the array.
Next: Write a NumPy program to change the data type of an array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}