NumPy Array Reshaping

M.Ramya

 Reshaping Arrays in NumPy

Reshaping refers to changing the shape or dimensions of an array.

An array’s shape defines the number of elements along each dimension.

By reshaping, you can:

Add or remove dimensions

Change the number of elements in each dimension (while keeping the total number of elements the same)

Reshape from 1-D to 2-D

program:

Convert a 1-D array with 12 elements into a 2-D array with 4 rows and 3 columns:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3)

print(newarr)

Output:

[[1 2 3 ][4 5 6][7 8 9][10 11 12]]

Reshape from 1-D to 3-D

Program:

Convert the same 1-D array into a 3-D array with 2 blocks, each containing 3 rows and 2 columns:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(2, 3, 2)

print(newarr)

Output:

[[[1 2][3 4][5 6]]     [[7 8][9 10][11 12]]]

Can We Reshape Into Any Shape?

Yes—but the total number of elements must remain the same.

For example, you can reshape an array with 8 elements into a shape of (2, 4) (2 rows, 4 columns), but not into (3, 3) since that would require 9 elements.

Program:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

# This will raise an error

newarr = arr.reshape(3, 3)

print(newarr)

Output:

[[1 2 3 4]
 [5 6 7 8]]

Does Reshape Return a Copy or a View?

You can check whether the reshaped array is a view (sharing the same data) or a copy by examining its .base attribute.

Program:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

print(arr.reshape(2, 4).base)

Output:

[1 2 3 4 5 6 7 8]

Unknown Dimension (Automatic Reshaping)

You can specify -1 for one dimension in reshape(). NumPy will automatically calculate the appropriate size for that dimension.

Program:

Convert a 1-D array with 8 elements into a 3-D array with dimensions (2, 2, 2):

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(2, 2, -1)

print(newarr)

Output:

[[[1 2][3 4]]  [[5 6][7 8]]]

Note: You can only specify -1 for one dimension at a time.

Flattening Arrays

Flattening refers to converting a multi-dimensional array into a 1-D array.

You can use reshape(-1) to flatten an array.

Program:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

newarr = arr.reshape(-1)

print(newarr)

Output:

[1 2 3 4 5 6]
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send