Python

πŸ“˜ Chapter 7: Array Reshaping and Manipulation in NumPy β€” Bend Data to Your Will

🧠 β€œYou don’t just work with data β€” you reshape it to fit your purpose.”

Welcome to Chapter 7 of your NumPy mastery journey!
So far, you’ve learned how to create, slice, broadcast, and summarize arrays. But what happens when the structure of the data isn’t quite what you need?

In data science and scientific computing, reshaping and rearranging arrays is as important as analyzing them.

Imagine:

  • Turning a 1D array into a matrix

  • Flattening a 2D matrix into a single row

  • Stacking arrays vertically or splitting them into parts

That’s what this chapter is all about: reshape, rearrange, and dominate.


πŸ” What We’ll Cover

  • reshape(), flatten(), ravel(), and transpose()

  • Concatenating arrays with hstack() and vstack()

  • Splitting arrays into parts

  • Practical use cases in machine learning, image processing, and more


🧱 1. Reshaping Arrays with reshape()

NumPy arrays are flexible β€” you can change their shape without changing the data.

πŸ”Ή Syntax:

array.reshape(new_shape)

πŸ“Œ Example:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6])
reshaped = a.reshape((2, 3))
print(reshaped)

 

Output:

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

 


🧻 2. Flattening Arrays

πŸ”Ή flatten() β€” Always returns a copy

b = reshaped.flatten()
print(b)  # [1 2 3 4 5 6]

πŸ”Ή ravel() β€” Returns a view (no copy if possible)

c = reshaped.ravel()
print(c)  # [1 2 3 4 5 6]

 


πŸ”„ 3. Transposing with transpose() and .T

The transpose flips rows and columns. It’s crucial in:

  • Linear algebra

  • Matrix multiplication

  • Neural networks

πŸ“Œ Example:

mat = np.array([
    [1, 2],
    [3, 4]
])

transposed = np.transpose(mat)
# or simply: mat.T

print(transposed)

Output:

[[1 3]
 [2 4]]

It flips rows β†’ columns and vice versa.


πŸ”— 4. Concatenating Arrays

Want to stack arrays side-by-side or top-to-bottom? NumPy’s got you.

πŸ”Έ Horizontal Stack: hstack()

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

print(np.hstack((a, b)))  # [1 2 3 4 5 6]

πŸ”Έ Vertical Stack: vstack()

print(np.vstack((a, b)))

Output:

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

πŸ”Έ Column Stack (convert 1D β†’ 2D then stack column-wise)

 

print(np.column_stack((a, b)))

 

Output:

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

πŸ“Œ Useful in dataset creation: combining features or labels.


βœ‚οΈ 5. Splitting Arrays

Just as you can merge arrays, you can split them too.

πŸ”Ή np.split() β€” Split into equal parts

arr = np.array([10, 20, 30, 40, 50, 60])
parts = np.split(arr, 3)
print(parts)  # [array([10, 20]), array([30, 40]), array([50, 60])]

πŸ”Ή np.hsplit() and np.vsplit() β€” For 2D arrays

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

# Split horizontally (columns)
print(np.hsplit(matrix, 2))

# Split vertically (rows)
print(np.vsplit(matrix, 2))

 


πŸ’‘ Real-Life Applications of Reshaping and Splitting

Task Function
Prepare image data for ML reshape() into (samples, height, width, channels)
Flatten before training a model flatten() or ravel()
Stack features and labels hstack(), column_stack()
Create batches of data split()
Normalize transposed data transpose() + mean()

🎨 Bonus: Reshape with -1 (Let NumPy Calculate)

a = np.arange(12)
reshaped = a.reshape((3, -1))  # Let NumPy infer the correct value
print(reshaped)

Output:

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

 


⚠️ Common Pitfalls to Avoid

Mistake Fix
Reshaping to incompatible shape Make sure new_shape.total_elements == original.size
Assuming ravel() returns a copy It returns a view!
Using reshape() without keeping track of original dimensions Always print .shape before and after
Concatenating arrays of mismatched shape Ensure axes align properly

πŸ“Œ Summary Table: Reshaping & Manipulation

Function Purpose
reshape() Change shape of an array
flatten() 1D copy of array
ravel() 1D view of array
transpose() / .T Swap rows and columns
hstack() / vstack() Stack horizontally/vertically
column_stack() Combine column-wise
split() / hsplit() / vsplit() Split arrays into parts

πŸ”š Wrapping Up Chapter 7

Congratulations! πŸŽ‰
You now hold the power to reshape arrays like a master sculptor.

Whether you’re preparing data for machine learning, formatting images for neural networks, or combining CSV columns β€” reshaping and manipulating arrays is the secret sauce behind every smart data pipeline.


πŸ”œ In Chapter 8: Advanced Indexing Techniques

We’ll explore:

  • Boolean masks

  • np.where(), np.select()

  • Fancy slicing and condition-based replacement

Leave a Reply

Your email address will not be published. Required fields are marked *