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)