Loading...
Represent a numerical table with an explicit shape and dtype. Predict the result of an operation before running it, especially when reducing an axis or applying a mask.
What you'll be able to do
NumPy’s ndarray stores numerical data with a shape and dtype. For this lesson, rows represent three days and columns represent two sensors. The array [[12,18],[14,22],[16,20]] has shape (3,2), two dimensions and six items. Shape is not the same as the total item count. numpy.ndim(array), numpy.shape(array) and numpy.size(array) answer different questions.
A dtype defines how items are represented. Fixed-width integer arrays can overflow where an ordinary Python int could grow, and floating arrays can round. Use an explicit suitable dtype when the task needs predictable representation; do not assume the same letter code means Python’s unlimited integer or a Boolean. Converting a floating array to an integer dtype can discard fractional information.
Arithmetic between same-shaped numerical arrays is normally elementwise. Adding 2 to every reading also uses NumPy’s broadcasting rules for a scalar. A reduction along axis 0 combines rows and returns one result per column, giving sensor means [14,20]. Along axis 1, it combines columns and returns daily means [15,18,18]. Without an axis, numpy.mean averages all six values, giving 17.
The expression readings>=20 creates a Boolean array of the same shape. Indexing readings with that mask returns the selected values [22,20] as a one-dimensional result. It does not retain a rectangular table with empty cells. Use parentheses and elementwise operators for compound array conditions; Python’s scalar and/or operators are not interchangeable with elementwise Boolean array operations.
import numpy as np
readings = np.array([[12, 18], [14, 22], [16, 20]], dtype=np.int64)
print(np.ndim(readings), np.shape(readings), np.size(readings))
print(np.mean(readings, axis=0).tolist())
print(np.mean(readings, axis=1).tolist())
print(float(np.mean(readings)))
print(readings[readings >= 20].tolist())
print(np.reshape(readings, (2, 3)).tolist())Scroll horizontally to see the full code or table.Reshaping reinterprets item positions in a new compatible shape; it does not calculate new readings or prove that the new rows have meaningful labels. Six items can form (2,3), but not (4,2). ravel produces a flattened one-dimensional representation; the result’s copy/view behaviour depends on the array, so make an explicit copy when independent mutation is required.
For numeric text files, specify a delimiter, header handling and dtype when loading. When saving, choose a format that preserves the required precision: fmt="%d" is suitable for this integer dataset, while an inadequate floating format could round information away. The StringIO example keeps the exercise in memory. On a real file, use the supplied task path and avoid overwriting the source during a cleaning exercise.
from io import StringIO
import numpy as np
source = StringIO('left,right\n12,18\n14,22\n16,20\n')
readings = np.loadtxt(source, delimiter=',', skiprows=1, dtype=np.int64)
saved = StringIO()
np.savetxt(saved, readings, delimiter=',', fmt='%d')
saved.seek(0)
restored = np.loadtxt(saved, delimiter=',', dtype=np.int64)
print(np.array_equal(readings, restored))
print(restored.tolist())Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.