๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 21 of 40
Lesson 21 of 40 Data Science Advanced โฑ 35 min

NumPy โ€” Arrays & Numerical Computing

Master NumPy arrays โ€” vectorised operations, broadcasting, fancy indexing, linear algebra, and performance vs plain Python loops.

Part 1: What You Will Learn

  • Create one- and two-dimensional NumPy arrays.
  • Use vectorised arithmetic instead of element-by-element Python loops.
  • Apply broadcasting and Boolean/fancy indexing.
  • Perform basic linear algebra with numpy.linalg.

Part 2: Key Concepts

NumPy stores homogeneous numerical data in compact arrays and performs many operations in optimized native code. Vectorisation describes expressing a whole-array operation at once rather than writing a Python loop for every element.

Part 3: Topic-Specific Code Example

# Install once: pip install numpy
import numpy as np

sales = np.array([
    [1200.0, 1350.0, 1280.0],
    [980.0, 1100.0, 1250.0],
    [1500.0, 1420.0, 1600.0],
])

print("Shape:", sales.shape)
print("Monthly totals:", sales.sum(axis=0))
print("Employee averages:", sales.mean(axis=1))

# Broadcasting: apply one growth factor per month.
growth = np.array([1.02, 1.03, 1.05])
forecast = sales * growth
print("Forecast:\n", forecast)

# Boolean indexing.
high_sales = sales[sales >= 1400]
print("Values >= 1400:", high_sales)

# Fancy indexing: choose row 0 and row 2.
selected = sales[[0, 2]]
print("Selected rows:\n", selected)

# Solve a small system of equations: A @ x = b.
A = np.array([[2.0, 1.0], [1.0, 3.0]])
b = np.array([8.0, 13.0])
x = np.linalg.solve(A, b)
print("Solution:", x)

Part 4: How the Example Works

axis=0 aggregates down rows to produce one result per month, while axis=1 produces one result per employee. Broadcasting multiplies every row by the same three monthly factors without manually repeating them. Boolean indexing returns only values matching a condition.

Part 5: Hands-On Practice

Mini project โ€” Exam Statistics. Store marks for five students across four subjects in a 2D NumPy array. Calculate each student average, each subject average, the highest mark, and all marks below 50. Add 5 bonus points using vectorised operations while capping values at 100 with np.clip().

Part 6: Next Steps

Run and modify the examples in Visual Studio 2026, then continue to Lesson 22. Return to Python Tutorial Home to review the complete curriculum.

๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’