TutorialsPythonNumPy Arrays

NumPy Arrays

Fast numerical computation with NumPy arrays — the engine behind Pandas

NumPy (Numerical Python) is the foundation of the entire Python data science stack. Pandas, Matplotlib, and scikit-learn are all built on NumPy. NumPy arrays are like Python lists but dramatically faster for numerical operations — they store data in contiguous memory and apply operations to entire arrays at once (vectorisation). For data analysts, you rarely use NumPy directly — Pandas handles most tasks. But understanding NumPy arrays helps you write faster Pandas code and understand why certain operations are fast or slow.

Examples

NumPy array basics
import numpy as np

# Create arrays
arr = np.array([45000, 18000, 62000, 9000, 51000])
zeros = np.zeros(5)          # [0. 0. 0. 0. 0.]
ones  = np.ones(5)           # [1. 1. 1. 1. 1.]
rng   = np.arange(1, 11)     # [1 2 3 4 5 6 7 8 9 10]
lin   = np.linspace(0, 1, 5) # [0.  0.25 0.5  0.75 1.  ]

# Shape and info
arr.shape    # (5,)  — 1D array with 5 elements
arr.dtype    # dtype('int64')
arr.size     # 5

# 2D array (like a table)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
matrix.shape  # (2, 3) — 2 rows, 3 columns
matrix[0, 1]  # 2 — row 0, col 1
💡 NumPy arrays require all elements to be the same type. Mixed types slow things down — Pandas handles that case.
Vectorised operations — the NumPy advantage
import numpy as np

sales = np.array([45000, 18000, 62000, 9000, 51000])

# Operations apply to every element instantly
sales * 1.1           # add 10% to all: [49500, 19800, ...]
sales / 100000        # convert to lakhs: [0.45, 0.18, ...]
sales > 20000         # [True, False, True, False, True]

# Filtering with boolean mask
high = sales[sales > 20000]   # [45000, 62000, 51000]

# Aggregations
np.sum(sales)     # 185000
np.mean(sales)    # 37000.0
np.median(sales)  # 45000.0
np.std(sales)     # standard deviation
np.min(sales)     # 9000
np.max(sales)     # 62000
np.percentile(sales, 75)   # 75th percentile

# This vectorised approach is 100x faster than a Python for loop
# on large arrays — this is why Pandas is fast

Key Points

  • import numpy as np — the universal convention
  • NumPy arrays are faster than Python lists because of contiguous memory and vectorisation
  • All elements in a NumPy array must be the same dtype
  • Boolean indexing: arr[arr > 20000] filters elements matching the condition
  • Pandas Series is built on NumPy array — .values returns the underlying NumPy array

Practice Question

What does sales[sales > 20000] return if sales = np.array([45000, 18000, 62000, 9000])?

Related Topics

Pandas SeriesThe one-dimensional Pandas data structure — a labelled array for a single columnPandas DataFramesThe core Pandas data structure — a 2D table with rows and columnsDescriptive Statistics in PythonCalculate mean, median, mode, variance, standard deviation and percentiles