Let’s discuss how to change the dimensions of an array. In NumPy, this can be achieved in many ways. Let’s discuss each of them.
Method #1: Using Shape()
Syntax :
array_name.shape()
Python3
import numpy as np
def main():
print('Initialised array')
gfg = np.array([1, 2, 3, 4])
print(gfg)
print('current shape of the array')
print(gfg.shape)
print('changing shape to 2,2')
gfg.shape = (2, 2)
print(gfg)
if __name__ == "__main__":
main()
|
Output:
Initialised array
[1 2 3 4]
current shape of the array
(4,)
changing shape to 2,2
[[1 2]
[3 4]]
Method #2: Using reshape()
The order parameter of reshape() function is advanced and optional. The output differs when we use C and F because of the difference in the way in which NumPy changes the index of the resulting array. Order A makes NumPy choose the best possible order from C or F according to available size in a memory block.

Difference between Order C and F
Syntax :
numpy.reshape(array_name, newshape, order= 'C' or 'F' or 'A')
Python3
import numpy as np
def main():
gfg = np.arange(1, 10)
print('initialised array')
print(gfg)
print('3x3 order C array')
print(np.reshape(gfg, (3, 3), order='C'))
print('3x3 order F array')
print(np.reshape(gfg, (3, 3), order='F'))
print('3x3 order A array')
print(np.reshape(gfg, (3, 3), order='A'))
if __name__ == "__main__":
main()
|
Output :
initialised array
[1 2 3 4 5 6 7 8 9]
3x3 order C array
[[1 2 3]
[4 5 6]
[7 8 9]]
3x3 order F array
[[1 4 7]
[2 5 8]
[3 6 9]]
3x3 order A array
[[1 2 3]
[4 5 6]
[7 8 9]]
Method #3 : Using resize()
The shape of the array can also be changed using the resize() method. If the specified dimension is larger than the actual array, The extra spaces in the new array will be filled with repeated copies of the original array.
Syntax :
numpy.resize(a, new_shape)
Python3
import numpy as np
def main():
gfg = np.arange(1, 10)
print('initialised array')
print(gfg)
gfg1=np.resize(gfg, (3, 3))
print('3x3 array')
print(gfg1)
gfg2=np.resize(gfg, (4, 4))
print('4x4 array')
print(gfg2)
gfg.resize(5, 5)
print('5x5 array')
print(gfg)
if __name__ == "__main__":
main()
|
Output :
initialised array
[1 2 3 4 5 6 7 8 9]
3x3 array
[[1 2 3]
[4 5 6]
[7 8 9]]
4x4 array
[[1 2 3 4]
[5 6 7 8]
[9 1 2 3]
[4 5 6 7]]
5x5 array
[[1 2 3 4 5]
[6 7 8 9 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
22 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...