Intermediate NumPy: Reshaping, Combining, and Broadcasting
Once you're comfortable with the basics, you'll find that real-world data is rarely in the perfect shape you need. Intermediate NumPy focuses on efficiently manipulating and combining arrays.
Reshaping Arrays
Changing the dimensions of an array is a common task. The
.reshape() method lets you do this, as long as the total number of elements stays the same.Pro-Tip: You can use
-1 to let NumPy automatically calculate one of the dimensions.Combining Arrays
You can join multiple arrays together using stacking functions.
np.vstack(): Stacks arrays vertically (as rows).np.hstack(): Stacks arrays horizontally (as columns).
The Magic of Broadcasting
Broadcasting is NumPy's way of dealing with operations on arrays of different shapes. It's the mechanism behind our first example where we added
2 to an entire array.Example: Adding a vector to a matrix
NumPy automatically "stretched" the
vector to match the matrix's shape, performing the addition across all rows.
Comments
Post a Comment