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.
python
# Create a 1D array of 12 elements
long_array = np.arange(12)

# Reshape it into a 3x4 array
reshaped_array = long_array.reshape(3, 4)
print(reshaped_array)
# Output:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

Pro-Tip: You can use -1 to let NumPy automatically calculate one of the dimensions.
# figure out the number of rows
auto_reshaped = long_array.reshape(-1, 4)
print(auto_reshaped)
# Output:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

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).
python
array_a = np.array([1, 2, 3])
array_b = np.array([4, 5, 6])

# Vertical Stack
v_stack = np.vstack((array_a, array_b))
print(v_stack)
# Output:
# [[1 2 3]
#  [4 5 6]]

# Horizontal Stack
h_stack = np.hstack((array_a, array_b))
print(h_stack)
# Output: [1 2 3 4 5 6]
Use code with caution.
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
python
matrix = np.array([[1, 2, 3], [4, 5, 6]])
vector = np.array([10, 20, 30])

result = matrix + vector
print(result)
# Output:
# [[11 22 33]
#  [14 25 36]]

NumPy automatically "stretched" the vector to match the matrix's shape, performing the addition across all rows.

Comments

Popular Posts