TutorialsPythonNumPy Arrays

NumPy Arrays

Fast numerical computing with NumPy arrays — the foundation under pandas

NumPy (Numerical Python) is the library that powers pandas under the hood. NumPy arrays (ndarray) are like Python lists but much faster for mathematical operations — because operations run on the entire array at once, not element by element. As a data analyst, you will use NumPy for: fast column-level math, generating test data, applying mathematical functions, and creating arrays for charts. You rarely use NumPy directly when pandas can do the job, but understanding it makes you a better pandas user.

Examples

NumPy array basics
import numpy as np

# Create arrays
arr = np.array([10, 20, 30, 40, 50])
arr2d = np.array([[1, 2, 3], [4, 5, 6]])  # 2D array

# Properties
arr.shape      # (5,)  — 5 elements, 1D
arr2d.shape    # (2, 3) — 2 rows, 3 columns
arr.dtype      # dtype('int64')
arr.size       # 5 — total elements

# Arithmetic (element-wise — no loop needed)
arr + 100      # array([110, 120, 130, 140, 150])
arr * 2        # array([20, 40, 60, 80, 100])
arr ** 2       # array([100, 400, 900, 1600, 2500])
arr / 1000     # array([0.01, 0.02, ...])

# vs Python list — lists do NOT broadcast like this
# [10, 20, 30] + 100  → TypeError
NumPy statistical functions and useful utilities
import numpy as np

salaries = np.array([45000, 55000, 72000, 38000, 95000, 61000])

# Statistics
np.mean(salaries)    # 61000.0
np.median(salaries)  # 58000.0
np.std(salaries)     # 18682.4
np.min(salaries)     # 38000
np.max(salaries)     # 95000
np.percentile(salaries, 75)  # 75th percentile = 69250.0

# Filter with boolean mask (same concept as pandas)
high = salaries[salaries > 60000]  # array([72000, 95000, 61000])

# Commonly used NumPy utilities in data work
np.where(salaries > 60000, "Senior", "Junior")
# array(['Junior','Junior','Senior','Junior','Senior','Senior'])

np.arange(0, 100, 10)   # [0, 10, 20, ..., 90]
np.linspace(0, 1, 5)    # [0.0, 0.25, 0.5, 0.75, 1.0]
np.zeros(5)              # [0. 0. 0. 0. 0.]
np.ones(3)               # [1. 1. 1.]
np.random.seed(42)
np.random.randint(1000, 5000, size=10)  # reproducible random
💡 np.where(condition, true_val, false_val) is the NumPy equivalent of Excel IF() — use it in pandas too.

Key Points

  • NumPy arrays are faster than Python lists for math — operations run on the whole array at once
  • arr.shape gives dimensions; arr.dtype gives the data type
  • Boolean masking: arr[arr > 60000] filters elements where condition is True
  • np.where(cond, a, b) — vectorised if-else, much faster than apply()
  • pandas Series and DataFrame columns are backed by NumPy arrays internally

Practice Question

What does arr * 2 do when arr = np.array([10, 20, 30])?