01.07 Lesson 7 of 10
48 minNumPy Arrays & Vectorization
Understand array shape, dtype, indexing, aggregation and element-wise operations.
By the end of this lesson
You will be able to
- Create one- and two-dimensional arrays.
- Inspect
shape,ndimanddtype. - Select values with slicing and boolean masks.
- Use vectorized operations and reductions.
Shape tells you how values are arranged
A one-dimensional array has one axis. A two-dimensional array has rows and columns. The shape tuple describes the size along each axis, while dtype describes the element type.
import numpy as np
counts = np.array([12, 18, 25, 19])
print(counts.shape) # (4,)
print(counts.ndim) # 1
print(counts.dtype)
matrix = np.array([[12, 18], [25, 19]])
print(matrix.shape) # (2, 2) Operate on arrays directly
Vectorized expressions operate on corresponding values without writing a Python loop. Boolean masks select values by condition. Aggregations such as sum and mean can operate over the whole array or along a chosen axis.
temperatures = np.array([18.0, 20.5, 22.0, 17.5])
above_20 = temperatures[temperatures > 20]
scaled = (temperatures - temperatures.mean()) / temperatures.std()
print(above_20)
print(scaled) Apply what you learned
ExerciseSummarize numeric sensor values
Use NumPy to calculate a basic summary and filter values without a row-by-row loop.
- Create an array of temperatures.
- Inspect its shape, dimensionality and dtype.
- Compute its mean and standard deviation.
- Select values above the mean using a boolean mask.
- Explain the axis argument with a two-dimensional example.
The summary is computed with NumPy operations and the selected values match the boolean condition.
Free references
Study resources
- 01 The absolute basics for beginners Article
Read array creation, indexing, operations, aggregation and broadcasting. Skip advanced topics for now.
Check your understanding
Self-test
-
Question 1
What does
shape == (3, 4)tell you?The array has three rows along its first axis and four columns along its second axis. -
Question 2
What is vectorization?
Expressing an operation over whole arrays so NumPy applies it efficiently without a Python loop over individual elements.
Completion check
Move on when
You can create, inspect, slice and aggregate arrays while explaining the shape of each result.