DEV Community

Ramya .C
Ramya .C

Posted on

🎯 Day 54 of My Data Analytics Journey

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[[1 2 3]
 [4 5 6]]
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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)
Enter fullscreen mode Exit fullscreen mode

Output:

[[1 2 3]
 [4 1 2]]
Enter fullscreen mode Exit fullscreen mode

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)))
Enter fullscreen mode Exit fullscreen mode

Output:

[[1 2 5 6]
 [3 4 7 8]]
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Vertical Stacking

print(np.vstack((a, b)))
Enter fullscreen mode Exit fullscreen mode

Output:

[[1 2]
 [3 4]
 [5 6]
 [7 8]]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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))
Enter fullscreen mode Exit fullscreen mode

Output:

[array([10, 20]), array([30, 40]), array([50, 60])]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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
Enter fullscreen mode Exit fullscreen mode

πŸš€ 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.


🏷️ Hashtags

DataAnalytics #Python #NumPy #MachineLearning #DataScience #LearningJourney

Top comments (0)