NumPy

Intermediate
14 min

What is NumPy?

NumPy provides efficient numerical computing in Python, handling large arrays and mathematical operations.

Key Components:

  • N-dimensional arrays
  • Mathematical functions
  • Linear algebra
  • Random number generation

Why it matters

Fast Calculations

Vectorized operations

Array Processing

Multi-dimensional data

Math Functions

Built-in mathematical operations

Random Data

Generate random numbers

Key Concepts

Array

Grid of values

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

Shape

Dimensions of array

Example: (3,4) for 3x4 matrix...

Broadcasting

Operations on different shapes

Example: arr + 5...

Vectorization

Operations on entire arrays

Example: arr * 2...

How to use

1

Import numpy

import numpy as np

2

Create array

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

3

Perform math

arr.mean(), arr.std()

4

Reshape

arr.reshape(3,1)

5

Index

arr[0], arr[1:3]

6

Use methods

np.sum(arr), np.max(arr)

Example

Goal: Calculate statistics
import numpy as np
arr = np.array([10,20,30,40,50])
mean = arr.mean()
std = arr.std()
print(f"Mean: {mean}, Std: {std}")
Result: Calculates and prints mean and standard deviation

Pro Tips

  • Use np.random: Generate random arrays
  • Axis parameter: Control row/column operations
  • Avoid loops: Use vectorized operations

Practice

Create a 3x3 matrix of random numbers and calculate its transpose