Shape Manipulation
Learn how to transform array dimensions, flatten multi-dimensional data, and combine arrays using stacking.
Learn how to transform array dimensions, flatten multi-dimensional data, and combine arrays using stacking. This hands-on tutorial focuses on practical implementation of shape manipulation concepts.
Module 5: Shape Manipulation
Data doesn't always come in the shape you need. Reshaping and stacks are essential when preparing data for machine learning models or visualization.
Lesson 11: Reshaping Arrays
Reshaping allows you to change the number of rows and columns without changing the data itself.
Rules for Reshaping:
- The total number of elements must remain the same.
- You can use
-1for one dimension, and NumPy will calculate it for you automatically.
Flattening vs Raveling:
.flatten(): Returns a 1D copy of the array..ravel(): Returns a 1D view (faster, but affects original).
Lesson 12: Joining & Splitting
Joining Arrays
Combining arrays is often done by "stacking".
np.concatenate((a, b)): Joins arrays along an existing axis.np.vstack((a, b)): Vertical stack (row-wise).np.hstack((a, b)): Horizontal stack (column-wise).
Splitting Arrays
Opposite of joining.
np.split(): Splits an array into multiple sub-arrays.np.vsplit(),np.hsplit(): Specialized vertical and horizontal splits.
Practice: Matrix Reshaping
Challenge: Create a target matrix of 100 elements (using np.arange(100)). Reshape it into a 10x10 matrix. Then, extract the first 5 rows and stack them horizontally with the last 5 rows.
Quiz
Question 1 of 5What does the -1 parameter do in reshape(5, -1)?
Key Takeaways
✅ Reshaping is only possible if the element count matches.
✅ .ravel() is faster than .flatten() because it doesn't copy data.
✅ Use vstack and hstack for intuitive array combining.