7 stages2 sections22 units

01.07 Lesson 7 of 10

48 min

NumPy 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, ndim and dtype.
  • 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

Exercise

Summarize numeric sensor values

Use NumPy to calculate a basic summary and filter values without a row-by-row loop.

  1. Create an array of temperatures.
  2. Inspect its shape, dimensionality and dtype.
  3. Compute its mean and standard deviation.
  4. Select values above the mean using a boolean mask.
  5. Explain the axis argument with a two-dimensional example.
Done when

The summary is computed with NumPy operations and the selected values match the boolean condition.

Free references

Study resources

1 links
  1. 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

2 questions
  1. Question 1

    What does shape == (3, 4) tell you?

  2. Question 2

    What is vectorization?

Completion check

Move on when

You can create, inspect, slice and aggregate arrays while explaining the shape of each result.

Quick find

Search Michi

Type to search every stage, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels