1.

Write a program for changing the dimension of a NumPy array.

Answer»

We can achieve this by overriding the shape attribute of the NumPy array.

Sample Solution:

import numpy as np

#Create NumPy array
arr = np.array([1,2,3,4,5,6,7,8,9])
print("Original Shape: ", arr.shape)

# Change the shape/dimension of the array
arr.shape = (3, 3)
print("Transformed Matrix :")
print(arr)
print("Transformed Shape: ",arr.shape)

Output:

Original Shape: (9,)
Transformed Matrix :
[[1 2 3]
[4 5 6]
[7 8 9]]
Transformed Shape: (3, 3)

In this approach, care has to be taken w.r.t the number of elements present in the original array before changing the dimensions. Otherwise, it will result in the ValueError as shown below:

import numpy as np

# We have array of 8 elements
arr = np.array([1,2,3,4,5,6,7,8])

# We are trying to convert the 1D array to a 3D array which expects 9 elements
arr.shape = (3, 3)
print(arr)

Running this code would result in:

1 import numpy as np
2 arr = np.array([1,2,3,4,5,6,7,8])
----> 3 arr.shape = (3, 3)
4 print(arr)

ValueError: cannot reshape array of size 8 into shape (3,3)


Discussion

No Comment Found