Python NumPy Introduction
In this page:
What is NumPy?
NumPy is the foundational library for numerical computing in Python, providing the ndarray type -- a fixed-type, multi-dimensional array that's dramatically faster and more memory-efficient than nested Python lists for numeric work, because its elements are stored contiguously in memory rather than as separate Python objects.
Example: What is NumPy?
import numpy as np
arr = np.array([1, 2, 3])
print(type(arr))
NumPy Array Attributes
Every NumPy array carries built-in metadata: .shape gives its dimensions as a tuple, .ndim gives the number of dimensions, and .size gives the total element count. Reading these attributes is how you quickly confirm an array's structure matches what a calculation expects, before running the calculation.
Example: NumPy Array Attributes
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr.shape, arr.ndim, arr.size)
Basic Mathematical Operations
NumPy applies arithmetic element-by-element across an entire array in a single vectorized operation (a + b adds every pair of corresponding elements at once), implemented in compiled C code under the hood. This is why NumPy math on large arrays runs orders of magnitude faster than an equivalent Python for loop.
Example: Basic Mathematical Operations
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b)
Array Data Types
Unlike a Python list, which can freely mix types, every NumPy array has one fixed dtype (like int32 or float64) shared by all its elements, chosen either automatically or explicitly via the dtype argument. Choosing a smaller dtype when precision allows can meaningfully cut an array's memory footprint.
Example: Array Data Types
import numpy as np
arr = np.array([1, 2, 3], dtype="float64")
print(arr.dtype)
Summary Statistics
NumPy arrays ship with built-in aggregate methods -- .sum(), .mean(), .max(), .min(), and more -- that compute across the whole array (or along a chosen axis for multi-dimensional data) far faster than manually looping and accumulating a running total in Python.
Example: Summary Statistics
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.sum(), arr.mean(), arr.max())
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB