Array Transformations

Back

Loading concept...

🔄 NumPy Array Transformations: The Shape-Shifting Magic Show!

Imagine you have a box of colorful building blocks. Sometimes you want to flip them upside down, spin them around, add extra blocks around the edges, or pick out just the corner pieces. That’s exactly what NumPy array transformations do!


🪞 Flipping and Rotating Arrays

The Mirror and Spinning Top Analogy

Think of your array like a photograph. You can:

  • Flip it like looking in a mirror (left becomes right, or top becomes bottom)
  • Rotate it like spinning a pinwheel (90°, 180°, 270°)

Flipping Arrays

Flip Left-Right (Horizontal Mirror)

import numpy as np

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

flipped = np.fliplr(arr)
# Result:
# [[3, 2, 1],
#  [6, 5, 4]]

🪞 Like writing your name and holding it up to a mirror!

Flip Up-Down (Vertical Mirror)

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

flipped = np.flipud(arr)
# Result:
# [[4, 5, 6],
#  [1, 2, 3]]

🪞 Like seeing your reflection in a puddle!

The Universal Flip Tool

# Flip along any axis you want!
np.flip(arr, axis=0)  # Same as flipud
np.flip(arr, axis=1)  # Same as fliplr
np.flip(arr)          # Flip everything!

Rotating Arrays

graph TD A["Original Array"] --> B["rot90 k=1: 90° counterclockwise"] A --> C["rot90 k=2: 180° rotation"] A --> D["rot90 k=3: 270° counterclockwise"]

Spin Your Array Like a Top!

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

# Rotate 90° counterclockwise
np.rot90(arr, k=1)
# [[2, 4],
#  [1, 3]]

# Rotate 180°
np.rot90(arr, k=2)
# [[4, 3],
#  [2, 1]]

# Rotate 270° (or 90° clockwise)
np.rot90(arr, k=3)
# [[3, 1],
#  [4, 2]]

💡 Pro Tip: k tells how many 90° turns. Negative k rotates clockwise!


🛡️ Padding Arrays

The Picture Frame Analogy

Imagine your array is a beautiful painting. Padding is like adding a frame around it — you can make the frame thick or thin, colorful or plain!

graph TD A["Original Array"] --> B["Add Frame/Padding"] B --> C["Constant: Same value everywhere"] B --> D["Edge: Copy the edges"] B --> E["Reflect: Mirror the edges"] B --> F["Wrap: Loop around"]

Basic Padding

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

# Add 1 layer of zeros around it
padded = np.pad(arr, pad_width=1)
# [[0, 0, 0, 0],
#  [0, 1, 2, 0],
#  [0, 3, 4, 0],
#  [0, 0, 0, 0]]

Different Padding Styles

Constant Padding (Custom Value)

np.pad(arr, 1, constant_values=9)
# [[9, 9, 9, 9],
#  [9, 1, 2, 9],
#  [9, 3, 4, 9],
#  [9, 9, 9, 9]]

Edge Padding (Copy the Border)

np.pad(arr, 1, mode='edge')
# [[1, 1, 2, 2],
#  [1, 1, 2, 2],
#  [3, 3, 4, 4],
#  [3, 3, 4, 4]]

Reflect Padding (Mirror Effect)

np.pad(arr, 1, mode='reflect')
# [[4, 3, 4, 3],
#  [2, 1, 2, 1],
#  [4, 3, 4, 3],
#  [2, 1, 2, 1]]

Wrap Padding (Loop Around)

np.pad(arr, 1, mode='wrap')
# [[4, 3, 4, 3],
#  [2, 1, 2, 2],
#  [4, 3, 4, 3],
#  [2, 1, 2, 1]]

💡 When to Use Each:

  • Constant: Neural networks, image borders
  • Edge: Image processing (no sharp edges)
  • Reflect: Signal processing
  • Wrap: Circular/periodic data

✂️ Insert and Delete Elements

The Train Car Analogy

Think of your array as a train with numbered cars. You can:

  • Insert new cars anywhere in the train
  • Delete cars you don’t need anymore

Inserting Elements

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

# Insert 99 at position 2
np.insert(arr, 2, 99)
# [1, 2, 99, 3, 4, 5]

🚂 Like adding a new car between car 2 and car 3!

Insert Multiple Values

np.insert(arr, 2, [99, 88, 77])
# [1, 2, 99, 88, 77, 3, 4, 5]

Insert in 2D Arrays

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

# Insert row at position 1
np.insert(arr2d, 1, [5, 6], axis=0)
# [[1, 2],
#  [5, 6],
#  [3, 4]]

# Insert column at position 1
np.insert(arr2d, 1, [5, 6], axis=1)
# [[1, 5, 2],
#  [3, 6, 4]]

Deleting Elements

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

# Delete element at position 2
np.delete(arr, 2)
# [1, 2, 4, 5]

✂️ Snip! The third element is gone!

Delete Multiple Elements

np.delete(arr, [1, 3])
# [1, 3, 5]

Delete Rows/Columns in 2D

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

# Delete row 1
np.delete(arr2d, 1, axis=0)
# [[1, 2, 3],
#  [7, 8, 9]]

# Delete column 1
np.delete(arr2d, 1, axis=1)
# [[1, 3],
#  [4, 6],
#  [7, 9]]

⚠️ Important: Both insert and delete return a new array. The original stays unchanged!


🔺 Triangle Extraction

The Pyramid Analogy

Imagine your 2D array is a square pyramid viewed from above. You can extract:

  • Upper triangle: The top half (above the diagonal)
  • Lower triangle: The bottom half (below the diagonal)
graph TD A["Square Matrix"] --> B["Upper Triangle<br>triu"] A --> C["Lower Triangle<br>tril"] B --> D["k=0: Include diagonal"] B --> E["k=1: Above diagonal"] C --> F["k=0: Include diagonal"] C --> G["k=-1: Below diagonal"]

Upper Triangle (triu)

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

np.triu(arr)
# [[1, 2, 3],
#  [0, 5, 6],
#  [0, 0, 9]]

Shift the Diagonal

# k=1: One above main diagonal
np.triu(arr, k=1)
# [[0, 2, 3],
#  [0, 0, 6],
#  [0, 0, 0]]

# k=-1: Include one below diagonal
np.triu(arr, k=-1)
# [[1, 2, 3],
#  [4, 5, 6],
#  [0, 8, 9]]

Lower Triangle (tril)

np.tril(arr)
# [[1, 0, 0],
#  [4, 5, 0],
#  [7, 8, 9]]

Shift the Diagonal

# k=-1: One below main diagonal
np.tril(arr, k=-1)
# [[0, 0, 0],
#  [4, 0, 0],
#  [7, 8, 0]]

# k=1: Include one above diagonal
np.tril(arr, k=1)
# [[1, 2, 0],
#  [4, 5, 6],
#  [7, 8, 9]]

Extract Triangle Indices

Sometimes you need the positions, not the values:

# Get indices of upper triangle
np.triu_indices(3)
# (array([0, 0, 0, 1, 1, 2]),
#  array([0, 1, 2, 1, 2, 2]))

# Use them to extract values
arr[np.triu_indices(3)]
# [1, 2, 3, 5, 6, 9]

💡 Real-World Uses:

  • Correlation matrices: Only upper triangle matters (symmetric)
  • Distance matrices: Avoid duplicates
  • Linear algebra: Triangular matrices solve equations faster

🎯 Quick Reference

Operation Function Example
Flip left-right np.fliplr(arr) Mirror horizontally
Flip up-down np.flipud(arr) Mirror vertically
Rotate 90° np.rot90(arr, k) k = number of rotations
Pad array np.pad(arr, width) Add border
Insert np.insert(arr, idx, val) Add elements
Delete np.delete(arr, idx) Remove elements
Upper triangle np.triu(arr, k) Above diagonal
Lower triangle np.tril(arr, k) Below diagonal

🌟 You Did It!

You’ve learned how to:

  • ✅ Flip arrays like mirrors
  • ✅ Rotate arrays like spinning tops
  • ✅ Pad arrays like picture frames
  • ✅ Insert and delete like train cars
  • ✅ Extract triangles like pyramid slices

These transformations are your toolkit for reshaping data exactly how you need it. Whether you’re processing images, preparing data for machine learning, or solving matrix problems — you’re now equipped!

🚀 Go transform some arrays!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.