Skip to main content
Pandas & NumPy
CHAPTER 04 Beginner

NumPy Array Operations

Updated: May 18, 2026
5 min read

# CHAPTER 4

NumPy Array Operations

1. Chapter Introduction

NumPy's power comes from operations on entire arrays — no Python loops needed. Element-wise arithmetic, matrix operations, concatenation, and statistics all run at C-speed via vectorization.

2. Arithmetic Operations (Element-wise)

python
123456789101112131415
import numpy as np

a = np.array([10, 20, 30, 40, 50])
b = np.array([2, 4, 5, 8, 10])

print(a + b)     # [12 24 35 48 60]
print(a - b)     # [8 16 25 32 40]
print(a * b)     # [20 80 150 320 500]
print(a / b)     # [5. 5. 6. 5. 5.]
print(a ** 2)    # [100 400 900 1600 2500]
print(a % 3)     # [1 2 0 1 2]

# Scalar operations (broadcast to all elements)
print(a + 100)   # [110 120 130 140 150]
print(a * 1.1)   # [11. 22. 33. 44. 55.]

3. Matrix Operations

python
12345678910111213141516
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Element-wise multiplication
print(A * B)          # [[5 12],[21 32]]

# Matrix multiplication (dot product)
print(A @ B)          # [[19 22],[43 50]]
print(np.dot(A, B))   # Same result

# Transpose
print(A.T)            # [[1 3],[2 4]]

# Determinant and inverse
print(np.linalg.det(A))   # -2.0
print(np.linalg.inv(A))   # [[-2. 1.],[1.5 -0.5]]

4. Statistical Operations

python
12345678910111213141516171819
scores = np.array([85, 92, 78, 96, 67, 88, 74, 91])

print(f"Mean:    {np.mean(scores):.2f}")    # 83.88
print(f"Median:  {np.median(scores):.2f}") # 86.5
print(f"Std Dev: {np.std(scores):.2f}")    # 9.43
print(f"Variance:{np.var(scores):.2f}")    # 88.86
print(f"Min:     {np.min(scores)}")        # 67
print(f"Max:     {np.max(scores)}")        # 96
print(f"Sum:     {np.sum(scores)}")        # 671
print(f"Cumsum:  {np.cumsum(scores)}")     # Running total

# Axis-based operations on 2D arrays
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

print(np.sum(matrix, axis=0))    # Column sums: [12 15 18]
print(np.sum(matrix, axis=1))    # Row sums: [6 15 24]
print(np.mean(matrix, axis=0))   # Column means: [4. 5. 6.]

5. Sorting and Searching

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

print(np.sort(arr))            # [1 1 2 3 4 5 6 9]
print(np.argsort(arr))         # Indices that would sort: [1 3 6 0 2 4 7 5]
print(np.argmax(arr))          # Index of max: 5
print(np.argmin(arr))          # Index of min: 1
print(np.where(arr > 4))       # Indices where condition true: (array([4,5,7]),)
print(arr[arr > 4])            # Values where True: [5 9 6]

6. Concatenation and Splitting

python
123456789101112131415161718
a = np.array([[1, 2, 3],
              [4, 5, 6]])
b = np.array([[7, 8, 9]])

# Stack rows (axis=0)
vstack = np.vstack([a, b])      # shape (3,3)
print(vstack)

# Stack columns (axis=1)
c = np.array([[10], [11]])
hstack = np.hstack([a, c])      # shape (2,4)
print(hstack)

# Split
arr = np.arange(12)
halves = np.array_split(arr, 3)  # Split into 3 equal parts
for h in halves:
    print(h)  # [0,1,2,3], [4,5,6,7], [8,9,10,11]

7. Mini Project: Student Marks Calculator

python
12345678910111213141516171819202122232425262728293031323334
import numpy as np

# Student marks: 5 subjects, 6 students
marks = np.array([
    [85, 92, 78, 88, 91],  # Alice
    [72, 68, 75, 80, 70],  # Bob
    [95, 97, 92, 94, 96],  # Carol
    [60, 55, 62, 58, 65],  # David
    [88, 84, 90, 87, 85],  # Eve
    [76, 79, 73, 81, 77],  # Frank
])

names = np.array(['Alice', 'Bob', 'Carol', 'David', 'Eve', 'Frank'])
subjects = np.array(['Math', 'Science', 'English', 'History', 'CS'])

totals = np.sum(marks, axis=1)
averages = np.mean(marks, axis=1)
ranks = np.argsort(averages)[::-1]  # Descending order

print("=" * 55)
print(f"{&#039;Rank':<6}{'Name':<10}{'Total':<8}{'Average':<10}{'Grade'}")
print("=" * 55)
for rank, idx in enumerate(ranks, 1):
    avg = averages[idx]
    grade = &#039;A+' if avg >= 90 else 'A' if avg >= 80 else 'B' if avg >= 70 else 'C'
    print(f"{rank:<6}{names[idx]:<10}{totals[idx]:<8}{avg:<10.1f}{grade}")

print("\nSubject Averages:")
for subj, avg in zip(subjects, np.mean(marks, axis=0)):
    print(f"  {subj}: {avg:.1f}")

print(f"\nClass Top Score: {np.max(marks)}")
print(f"Class Low Score: {np.min(marks)}")
print(f"Pass rate (avg>=60): {np.mean(averages >= 60)*100:.0f}%")

8. Common Mistakes

  • A * B vs A @ B: * is element-wise, @ is matrix multiplication. For linear algebra, always use @ or np.dot().
  • axis=0 vs axis=1: axis=0 operates across rows (column-wise result). axis=1 operates across columns (row-wise result).

9. MCQs

Question 1

a @ b for arrays performs?

Question 2

np.sum(matrix, axis=0) computes?

Question 3

np.argsort(arr) returns?

Question 4

np.vstack([a, b]) stacks?

Question 5

np.cumsum([1,2,3,4]) returns?

Question 6

np.where(arr > 5) returns?

Question 7

arr

Question 8

np.linalg.inv(A) computes?

Question 9

np.hstack([a, b]) stacks?

Question 10

np.argmax(arr) returns?

10. Interview Questions

  • Q: What is the difference between * and @ for NumPy arrays?
  • Q: Explain axis parameter in NumPy operations.

11. Summary

NumPy array operations are fully vectorized — no loops needed. Arithmetic is element-wise. Matrix multiplication uses
@. Statistical functions accept axis to operate row-wise or column-wise. argsort` gives the ranking indices essential for ranked output.

12. Next Chapter Recommendation

In Chapter 5: NumPy Indexing and Slicing, we master array access patterns — simple indexing, multi-dimensional slicing, boolean indexing, and fancy indexing.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·