#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read min read

Array Reshaping and Manipulation

Learn to transform and manipulate array shapes and structures

Array Reshaping and Manipulation

Reshaping Arrays

Change array shape without changing data.

reshape()

code.py
import numpy as np

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

Output:

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

Important: Total elements must stay same (6 = 2×3).

Auto-calculate Dimension

Use -1 to let NumPy figure out one dimension.

code.py
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
reshaped = arr.reshape(2, -1)
print("Shape:", reshaped.shape)
print(reshaped)

Output:

Shape: (2, 4) [[1 2 3 4] [5 6 7 8]]

What -1 does: NumPy calculates: 8 elements ÷ 2 rows = 4 columns.

Flattening Arrays

Convert multi-dimensional to 1D.

flatten()

code.py
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
flat = matrix.flatten()
print(flat)

Output: [1 2 3 4 5 6]

ravel()

Similar to flatten but faster (usually).

code.py
import numpy as np

matrix = np.array([[1, 2], [3, 4]])
flat = matrix.ravel()
print(flat)

Difference:

  • flatten() creates copy
  • ravel() creates view (changes affect original)

Transposing

Swap rows and columns.

code.py
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("Original shape:", matrix.shape)
print(matrix)

transposed = matrix.T
print("Transposed shape:", transposed.shape)
print(transposed)

Output:

Original shape: (2, 3) [[1 2 3] [4 5 6]] Transposed shape: (3, 2) [[1 4] [2 5] [3 6]]

Use case: Change from row-based to column-based data.

Stacking Arrays

Combine multiple arrays.

Vertical Stack (vstack)

Stack arrays vertically (row-wise).

code.py
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
vstacked = np.vstack([arr1, arr2])
print(vstacked)

Output:

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

Horizontal Stack (hstack)

Stack arrays horizontally (column-wise).

code.py
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
hstacked = np.hstack([arr1, arr2])
print(hstacked)

Output: [1 2 3 4 5 6]

Column Stack

code.py
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
col_stacked = np.column_stack([arr1, arr2])
print(col_stacked)

Output:

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

Splitting Arrays

Divide array into parts.

Split Evenly

code.py
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
parts = np.split(arr, 3)
print("Part 1:", parts[0])
print("Part 2:", parts[1])
print("Part 3:", parts[2])

Output:

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

Split at Indices

code.py
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
parts = np.split(arr, [3, 6])
print("Part 1:", parts[0])
print("Part 2:", parts[1])
print("Part 3:", parts[2])

Output:

Part 1: [1 2 3] Part 2: [4 5 6] Part 3: [7 8]

What [3, 6] means: Split at index 3 and index 6.

Adding Dimensions

newaxis

code.py
import numpy as np

arr = np.array([1, 2, 3])
print("Original shape:", arr.shape)

col = arr[:, np.newaxis]
print("Column shape:", col.shape)
print(col)

row = arr[np.newaxis, :]
print("Row shape:", row.shape)
print(row)

Output:

Original shape: (3,) Column shape: (3, 1) [[1] [2] [3]] Row shape: (1, 3) [[1 2 3]]

expand_dims

code.py
import numpy as np

arr = np.array([1, 2, 3])
expanded = np.expand_dims(arr, axis=0)
print("Shape:", expanded.shape)

Output: Shape: (1, 3)

Repeating Elements

repeat()

code.py
import numpy as np

arr = np.array([1, 2, 3])
repeated = np.repeat(arr, 3)
print(repeated)

Output: [1 1 1 2 2 2 3 3 3]

tile()

code.py
import numpy as np

arr = np.array([1, 2, 3])
tiled = np.tile(arr, 3)
print(tiled)

Output: [1 2 3 1 2 3 1 2 3]

Difference:

  • repeat: Each element repeated
  • tile: Entire array repeated

Concatenate

Join arrays along existing axis.

code.py
import numpy as np

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

vertical = np.concatenate([arr1, arr2], axis=0)
print("Vertical:")
print(vertical)

horizontal = np.concatenate([arr1, arr2], axis=1)
print("Horizontal:")
print(horizontal)

Output:

Vertical: [[1 2] [3 4] [5 6] [7 8]] Horizontal: [[1 2 5 6] [3 4 7 8]]

Deleting Elements

delete()

code.py
import numpy as np

arr = np.array([10, 20, 30, 40, 50])
result = np.delete(arr, [1, 3])
print(result)

Output: [10 30 50]

What this does: Removes elements at index 1 and 3.

Inserting Elements

code.py
import numpy as np

arr = np.array([1, 2, 3, 4])
result = np.insert(arr, 2, 99)
print(result)

Output: [1 2 99 3 4]

What this does: Inserts 99 at index 2.

Practice Example

The scenario: Reshape and manipulate sales data for analysis.

code.py
import numpy as np

weekly_sales = np.array([100, 150, 120, 180, 160, 140, 200, 190, 170, 210, 220, 195])

print("Original data (12 weeks):")
print(weekly_sales)
print()

quarterly = weekly_sales.reshape(4, 3)
print("Reshaped (4 quarters, 3 weeks each):")
print(quarterly)
print()

quarter_totals = quarterly.sum(axis=1)
print("Total per quarter:", quarter_totals)
print()

transposed = quarterly.T
print("Transposed (weeks as rows):")
print(transposed)
print()

first_half = weekly_sales[:6]
second_half = weekly_sales[6:]
print("First half:", first_half)
print("Second half:", second_half)
print()

comparison = np.column_stack([first_half, second_half])
print("Week-by-week comparison:")
print(comparison)
print()

flat = quarterly.flatten()
print("Back to flat:", flat)
print()

doubled = np.tile(weekly_sales[:3], 4)
print("First 3 weeks repeated 4 times:")
print(doubled)

What this demonstrates:

  1. Reshape 1D to 2D (quarters)
  2. Calculate quarterly totals
  3. Transpose for different view
  4. Split into halves
  5. Compare corresponding weeks
  6. Flatten back to 1D
  7. Repeat pattern

Squeeze

Remove dimensions of size 1.

code.py
import numpy as np

arr = np.array([[[1, 2, 3]]])
print("Original shape:", arr.shape)

squeezed = np.squeeze(arr)
print("Squeezed shape:", squeezed.shape)
print(squeezed)

Output:

Original shape: (1, 1, 3) Squeezed shape: (3,) [1 2 3]

Key Points to Remember

reshape() changes shape but total elements must stay same. Use -1 to auto-calculate one dimension.

flatten() and ravel() convert to 1D. flatten() copies, ravel() creates view.

Transpose with .T swaps rows and columns. Useful for changing data orientation.

vstack() stacks vertically, hstack() horizontally. concatenate() joins along specific axis.

split() divides arrays. delete() removes elements. insert() adds elements.

Common Mistakes

Mistake 1: reshape with wrong total

code.py
arr = np.array([1, 2, 3, 4, 5])
arr.reshape(2, 3)  # Error! 5 ≠ 2×3

Mistake 2: Modifying ravel view

code.py
flat = matrix.ravel()
flat[0] = 99  # Changes original matrix!

Use flatten() if you don't want this.

Mistake 3: Wrong stack function

code.py
np.hstack([[1], [2]])  # Creates [1 2]
np.vstack([[1], [2]])  # Creates [[1], [2]]

Mistake 4: Forgetting axis

code.py
np.concatenate([arr1, arr2])  # Default axis=0
np.concatenate([arr1, arr2], axis=1)  # Horizontal

What's Next?

You now know array manipulation. Next, you'll learn linear algebra with NumPy - matrix operations, solving equations, eigenvalues, and more.

SkillsetMaster - AI, Web Development & Data Analytics Courses