Skip to main content

NumPy Tutorial: Core Concepts

NumPy (Numerical Python) is the fundamental library for numerical computing in Python. It provides powerful N-dimensional array objects, tools for integrating with C/C++ and Fortran code, and a wide range of mathematical functions.

In this tutorial, we'll cover the core concepts of NumPy, including array creation, indexing, slicing, broadcasting, universal functions, and linear algebra.


📥 Download the Sample Data

These files are used in the I/O and array manipulation sections of the tutorial.

FileDescriptionLink
sensor_readings.csvSensor temperature, humidity & pressure readings (1000 rows)Download
sample_data.txtTab-separated values for loadtxt/savetxt examples (50 rows)Download

💡 Tip: Save these files to your working directory. Use np.loadtxt() for text files and np.genfromtxt() for CSV files with headers.


1. Introduction to NumPy

At the heart of NumPy is the ndarray (N-dimensional array) object — a fast, flexible container for large datasets.

Key Features of NumPy:

  • N-dimensional arrays: Homogeneous, fast, memory-efficient arrays
  • Vectorization: Express operations on entire arrays without explicit loops
  • Broadcasting: Perform operations on arrays of different shapes
  • Universal functions (ufuncs): Fast element-wise mathematical operations
  • Linear algebra: Matrix operations, decompositions, eigenvalues
  • Random number generation: Sample from probability distributions

2. Installing NumPy

You can install NumPy via pip:

pip install numpy

3. Importing NumPy

import numpy as np

This imports NumPy as np, which is the standard convention.


4. Creating Arrays

From a Python list

import numpy as np

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

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

Using built-in creation functions

# Array of zeros
zeros = np.zeros((3, 4)) # 3x4 array of zeros

# Array of ones
ones = np.ones((2, 3)) # 2x3 array of ones

# Identity matrix
identity = np.eye(4) # 4x4 identity matrix

# Range of values
range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]

# Linearly spaced values
linspace = np.linspace(0, 1, 5) # [0.0, 0.25, 0.5, 0.75, 1.0]

# Random values
random_arr = np.random.rand(3, 3) # 3x3 uniform [0, 1)

5. Array Attributes

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

print(arr.shape) # (2, 3) — dimensions
print(arr.ndim) # 2 — number of axes
print(arr.size) # 6 — total elements
print(arr.dtype) # int64 — data type
print(arr.itemsize) # 8 — bytes per element
print(arr.nbytes) # 48 — total bytes consumed

6. Indexing and Slicing

Basic indexing

arr = np.array([10, 20, 30, 40, 50])

print(arr[0]) # 10
print(arr[-1]) # 50
print(arr[1:4]) # [20, 30, 40]

Multi-dimensional indexing

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

print(matrix[0, 1]) # 2 — row 0, column 1
print(matrix[1]) # [4, 5, 6] — row 1
print(matrix[:, 0]) # [1, 4, 7] — column 0
print(matrix[0:2, 1:3]) # [[2, 3], [5, 6]] — submatrix

Fancy indexing

arr = np.array([10, 20, 30, 40, 50])
indices = [0, 2, 4]
print(arr[indices]) # [10, 30, 50]

# Boolean indexing
mask = arr > 25
print(arr[mask]) # [30, 40, 50]

7. Reshaping and Transposing

arr = np.arange(12)

# Reshape to 3x4
reshaped = arr.reshape(3, 4)

# Flatten to 1D
flat = reshaped.flatten()

# Transpose
matrix = np.array([[1, 2], [3, 4]])
transposed = matrix.T # [[1, 3], [2, 4]]

# Add/remove dimensions
col_vector = arr[:, np.newaxis] # adds a new axis
squeezed = np.squeeze(col_vector) # removes single-dimension axes

8. Broadcasting

Broadcasting allows NumPy to perform operations on arrays of different shapes.

# Scalar + array
arr = np.array([1, 2, 3])
result = arr + 10 # [11, 12, 13]

# 1D + 2D
matrix = np.ones((3, 3))
row = np.array([1, 2, 3])
result = matrix + row # adds row to each row of matrix

# Column + row
col = np.array([[1], [2], [3]])
row = np.array([10, 20, 30])
result = col + row # broadcasting in both directions

9. Universal Functions (ufuncs)

Ufuncs are fast, element-wise operations on arrays.

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

# Trigonometric
print(np.sin(arr))
print(np.cos(arr))

# Exponential and logarithmic
print(np.exp(arr))
print(np.log(arr))

# Power and square root
print(np.sqrt(arr))
print(np.power(arr, 2))

# Absolute value
print(np.abs([-1, -2, -3]))

10. Aggregation and Statistics

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

print(np.sum(arr)) # 21 — total sum
print(np.mean(arr)) # 3.5 — mean
print(np.std(arr)) # 1.7078 — standard deviation
print(np.min(arr)) # 1 — minimum
print(np.max(arr)) # 6 — maximum

# Along an axis
print(np.sum(arr, axis=0)) # [5, 7, 9] — sum columns
print(np.sum(arr, axis=1)) # [6, 15] — sum rows

11. Linear Algebra

# Matrix multiplication
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
C = np.dot(A, B) # or A @ B
print(C)
# [[19 22]
# [43 50]]

# Determinant
det = np.linalg.det(A)

# Inverse
inv = np.linalg.inv(A)

# Eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(A)

# Solve linear system Ax = b
b = np.array([1, 2])
x = np.linalg.solve(A, b)

12. Random Number Generation

# Set seed for reproducibility
np.random.seed(42)

# Uniform distribution [0, 1)
uniform = np.random.rand(3, 3)

# Normal distribution
normal = np.random.randn(1000)

# Integers
integers = np.random.randint(0, 10, size=(3, 3))

# Choice from array
choices = np.random.choice([1, 2, 3, 4, 5], size=10)

# Shuffle array
arr = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr)

13. Input / Output

# Save to binary .npy format
arr = np.array([1, 2, 3, 4, 5])
np.save('array.npy', arr)

# Load from .npy
loaded = np.load('array.npy')

# Save multiple arrays
np.savez('arrays.npz', a=arr, b=arr * 2)

# Save to text
np.savetxt('array.csv', arr, delimiter=',')

# Load from text
loaded_txt = np.loadtxt('array.csv', delimiter=',')

Summary

NumPy is the foundation of scientific computing in Python. Here's a recap of the key concepts we covered:

  • np.array(): Create arrays from Python lists
  • np.zeros(), np.ones(), np.eye(): Special arrays
  • np.arange(), np.linspace(): Sequences
  • .shape, .dtype, .ndim: Array attributes
  • Indexing and slicing: Access elements and subarrays
  • .reshape(), .T: Reshape and transpose
  • Broadcasting: Operations on different-shaped arrays
  • Ufuncs: Fast element-wise math (np.sin, np.exp, etc.)
  • np.sum(), np.mean(), np.std(): Aggregations
  • np.dot(), np.linalg: Linear algebra
  • np.random: Random number generation