Definition
A class's marks in five subjects form a table: 40 students by 5 subjects. How do you grab one student's row, one subject's column, or every student who scored above 90 in maths, in one short expression?
An array's shape is a tuple giving its size along each axis: a (40, 5) array has 40 rows and 5 columns. Indexing picks single elements with arr[row, col]; slicing picks ranges with start:stop:step along each axis; boolean indexing picks elements where a condition is True; and reshape changes the shape without changing the data.
In simple words
Think of a cinema seating chart. arr[3, 7] is row 3, seat 7. arr[3, :] is all of row 3. arr[:, 7] is seat 7 in every row. arr[arr > 90] is every seat whose ticket cost more than 90.
Overview
- An array's shape is a tuple giving the length of each axis, such as (40, 5).
- Indexing reaches single elements; slicing reaches blocks; both use one index per axis.
- Slices of NumPy arrays are views: changing them changes the original array.
- reshape changes the shape without changing the data, as long as the total size stays the same.
- -1 in reshape lets NumPy work out one dimension automatically.
- Shape errors are the most common bug in machine-learning code, so print .shape often.
Why it matters
Selecting the right part of the data is most of practical data work. Images, tables and batches of training examples are all multi-dimensional arrays, and every library expects you to slice, mask and reshape them fluently.
Key terms
- Shape
- A tuple of sizes along each axis, such as (40, 5).
- Axis
- A dimension: axis 0 runs down the rows, axis 1 across the columns.
- Slice
- A range selection start:stop:step, excluding stop.
- Boolean mask
- An array of True/False used to select matching elements.
- View versus copy
- A slice is usually a view sharing memory with the original; .copy() makes an independent array.
- reshape
- Rearranging the same elements into a new shape with the same total size.
Types
NumPy offers several kinds of indexing, plus tools that change shape. Each type selects or rearranges data differently.
1. Basic (integer) indexing
Selecting single elements with one integer per axis.
- How it works: a[2] gives the third element of a 1-D array; m[1, 3] gives row 1, column 3 of a 2-D array; negative indexes count from the end.
- Example: marks[0, -1] is the first student's last subject mark.
- When to use it: Use it to read or change individual values.
2. Slicing
Selecting ranges with start:stop:step on each axis.
- How it works: m[:10, 1:3] takes the first 10 rows and columns 1–2; the result is a view sharing memory, so use .copy() to keep it separate.
- Example: image[100:200, 50:150] crops a 100 × 100 region from a photo.
- When to use it: Use it to crop images, take the first rows of a data set or split features from labels.
3. Boolean (mask) indexing
Selecting elements with an array of True/False values of the same shape.
- How it works: A condition like a > 50 builds a mask; a[mask] returns only the elements where it is True, as a new copy; masks combine with & and |.
- Example: marks[marks < 33] lists failing marks; temps[(temps > 30) & (temps < 40)] keeps warm days.
- When to use it: Use it to filter data by conditions and to replace values, e.g. a[a < 0] = 0.
4. Fancy (integer-array) indexing
Selecting elements with a list or array of indexes.
- How it works: a[[0, 3, 5]] picks those positions in that order; with 2-D arrays, rows and columns can each be chosen by lists; the result is a copy.
- Example: X[np.argsort(scores)[::-1][:5]] selects the five highest-scoring rows.
- When to use it: Use it to reorder data, take random samples or pick top-k results.
5. Reshaping tools
reshape, ravel/flatten, transpose (.T), expand_dims, squeeze and concatenate/stack.
- How it works: reshape(28, 28) turns 784 pixels into an image; .T swaps rows and columns; expand_dims adds an axis of length 1; stack joins arrays along a new axis.
- Example: digits.images[0].reshape(-1) flattens an 8 × 8 digit into 64 features for a classifier.
- When to use it: Use them to match the input shape a model or function expects.
Explained in detail
Shapes and axes
A 1D array of 5 marks has shape (5,). A table of 40 students and 5 subjects has shape (40, 5): axis 0 is the students, axis 1 the subjects. A colour photo of 480 × 640 pixels has shape (480, 640, 3), the last axis holding red, green and blue. Many functions take an axis argument. marks.mean(axis=0) averages down the rows, giving one mean per subject, shape (5,); marks.mean(axis=1) averages across each row, giving one mean per student, shape (40,). A helpful rule: the axis you name is the one that disappears.
Indexing and slicing in 2D
| Expression | Selects | Result shape for (40, 5) |
|---|---|---|
| m[0, 2] | Student 0, subject 2 | A single value |
| m[0] | Every subject for student 0 | (5,) |
| m[:, 2] | Subject 2 for every student | (40,) |
| m[:10, :3] | First 10 students, first 3 subjects | (10, 3) |
| m[::2] | Every second student | (20, 5) |
| m[:, [0, 4]] | Subjects 0 and 4 (fancy indexing) | (40, 2) |
Boolean masks
A comparison on an array produces a mask of the same shape: maths = m[:, 0]; maths > 90 is True where the condition holds. Using the mask as an index selects those elements: maths[maths > 90]. Masks can select whole rows: m[maths > 90] gives every subject for the students who scored above 90 in maths. Combine conditions with & (and), | (or) and ~ (not), with brackets around each condition, because these operators bind more tightly than comparisons: (maths > 90) & (m[:, 1] > 80). Python's and and or do not work on arrays. Masks are also used to change values: marks[marks < 0] = 0 replaces impossible negative marks.
Views, copies and reshaping
- Basic slices return views: changing first_ten = m[:10] also changes m. Use m[:10].copy() for independent data.
- Boolean and fancy indexing always return copies.
- arr.reshape(4, 3) rearranges 12 elements into 4 rows of 3; one dimension may be -1 to let NumPy work it out.
- arr.flatten() or arr.ravel() turns any array into 1D, as when a 28 × 28 image becomes 784 features.
- arr[np.newaxis] or arr.reshape(1, -1) adds an axis, often needed when a model expects a batch.
How it works
- Print arr.shape first, and name what each axis means.
- Use arr[i, j] for one value and : for whole rows or columns.
- Build boolean masks with comparisons and combine with &, | and ~.
- Use .copy() when you must change a slice without changing the original.
- Reshape to the shape a function or model expects, checking the total size matches.
In code
import numpy as np
rng = np.random.default_rng(3)
marks = rng.integers(30, 100, size=(6, 3)) # 6 students x 3 subjects: maths, science, english
print("Shape:", marks.shape)
print(marks)
print("Student 0:", marks[0])
print("Maths column:", marks[:, 0])
print("Subject means (axis=0):", marks.mean(axis=0).round(1))
print("Student means (axis=1):", marks.mean(axis=1).round(1))
toppers = marks[(marks[:, 0] > 70) & (marks[:, 1] > 60)]
print("Rows with maths > 70 and science > 60:\n", toppers)
flat = marks.reshape(-1)
print("Flattened shape:", flat.shape, " back to:", flat.reshape(3, 6).shape)Output
Shape: (6, 3) [[86 35 42] [46 42 86] [90 70 32] [36 53 60] [73 63 48] [41 78 81]] Student 0: [86 35 42] Maths column: [86 46 90 36 73 41] Subject means (axis=0): [62. 56.8 58.2] Student means (axis=1): [54.3 58. 64. 49.7 61.3 66.7] Rows with maths > 70 and science > 60: [[90 70 32] [73 63 48]] Flattened shape: (18,) back to: (3, 6)
Try it yourself
Finding the science scholarship list
A school stores marks as a (40, 5) array: students by subjects.
What shape results?
For an array m of shape (40, 5):
m.mean(axis=0)
m.mean(axis=1)
m[3]
m[:, 0]
m[:10]
Common mistakes
- Mixing up axis 0 and axis 1 in aggregations.
- Changing a slice and unexpectedly changing the original array.
- Using and/or instead of &/| for array conditions.
Check yourself
Summary
- Shape lists sizes per axis; name what each axis means.
- Index, slice and mask to select exactly the data you need.
- Watch views versus copies, and reshape to what models expect.
Finished reading?
Sources: NumPy: the absolute basics for beginners · Python for Data Analysis, 3rd edition (Wes McKinney)