NumPy Reshaping, Resizing, Stacking & Splitting Arrays
Today, I dived deep into NumPy, one of the most powerful Python libraries for data manipulation and numerical computing.
Hereโs what I learned ๐
๐น 1๏ธโฃ Reshaping Arrays
Reshaping means changing the shape (rows ร columns) of an existing array without changing the data.
Github:https:https://github.com/ramyacse21/numpy_workspace/blob/main/reshape%20in%20numpy.py
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped = arr.reshape(2, 3)
print(reshaped)
Output:
[[1 2 3]
[4 5 6]]
๐ The 1D array is reshaped into a 2D array (2 rows, 3 columns).
๐น 2๏ธโฃ Resizing Arrays
Resizing creates a new array shape โ it adds or removes elements to match the new size.
arr = np.array([1, 2, 3, 4])
resized = np.resize(arr, (2, 3))
print(resized)
Output:
[[1 2 3]
[4 1 2]]
Notice how elements repeat when needed to fill the new shape.
๐น 3๏ธโฃ Stacking Arrays
Stacking means joining two or more arrays together.
๐ Horizontal Stacking
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.hstack((a, b)))
Output:
[[1 2 5 6]
[3 4 7 8]]
๐ Vertical Stacking
print(np.vstack((a, b)))
Output:
[[1 2]
[3 4]
[5 6]
[7 8]]
๐น 4๏ธโฃ Splitting Arrays
Splitting means dividing an array into multiple sub-arrays.
arr = np.array([10, 20, 30, 40, 50, 60])
print(np.split(arr, 3))
Output:
[array([10, 20]), array([30, 40]), array([50, 60])]
๐น 5๏ธโฃ Working with Different Dimensions
Understanding 1D, 2D, and 3D arrays is essential:
# 1D
arr1 = np.array([1, 2, 3])
# 2D
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
# 3D
arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr1.ndim, arr2.ndim, arr3.ndim) # Output: 1 2 3
๐ Key Takeaway
These NumPy operations help reshape and structure data efficiently โ a critical skill for every Data Analyst or Data Scientist working with large datasets.
Top comments (0)