slicing of array in python

???? Reshaping of Array in Python

To reshape an array means to change its dimensions (e.g., from 1D to 2D, 2D to 3D, etc.) without changing the data.

This is mainly done using NumPy, a powerful Python library for numerical operations.


? Step 1: Import NumPy

import numpy as np

? Create a 1D Array

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

? Reshape to 2D Array

# Reshape to 2 rows and 3 columns
reshaped = arr.reshape(2, 3)
print(reshaped)

Output:

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

? Reshape to 3D Array

# Reshape to 3D: 1 block, 2 rows, 3 columns
reshaped_3d = arr.reshape(1, 2, 3)
print(reshaped_3d)

Output:

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

? Automatically Calculate a Dimension using -1

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

# Let NumPy automatically calculate the number of columns
reshaped = arr.reshape(2, -1)
print(reshaped)

Output:

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

Note: The total number of elements must match. You can’t reshape an array into a shape that requires more or fewer elements.


? Invalid Example:

# arr has 6 elements; this will raise an error
arr.reshape(4, 2)

 

  All Comments:   0