Array Creation and Shapes
Build the data containers confidently
Manufacturing arrays — zeros, ones, arange, linspace, random fills, and reshaping between shapes — is the everyday grammar of feature matrices and images.
What you will learn
- Create arrays from constructors and existing data
- Reshape and flatten without surprises
- Control dtype and understand its cost
What is this?
Arrays are born from constructors (np.zeros, np.ones, np.full, np.empty, np.arange, np.linspace, np.random.*), conversions of nested lists (np.array), or textual/matrix IO. Once you have one, `.shape`, `.reshape`, `.ravel`, `.T` and `.astype` reshape and retype it. Shape literacy — knowing what (n, d) means — is the core of writing correct matrix code.
Why do you need it?
- Most data arrives as nested lists/records; conversion is step one of analysis.
- np.linspace/np.arange create the number lines used as x-axes and ranges everywhere.
- reshape errors (mismatched dimension counts) are among the most common numpy bugs.
- dtype control halves memory and changes results — an advanced-looking deal that's basic.
Mental model
Packing boxes into configured shelving
reshape without copying data
The same boxes re-arranged into a different shelf grid: total count must match, and the boxes (elements) just get re-laid-out. reshape re-views the same memory; ravel flattens to one row.
How it works
- np.zeros((3,2)) / np.ones_like(x) / np.full((3,), 7) create filled arrays with exact shapes.
- np.arange(stop) or np.arange(start, stop, step) give integer ranges; np.linspace(a, b, n) splits a..b into n points.
- np.array(list_of_lists, dtype=...) builds from nested Python data, inferring dtype.
- arr.reshape(n, -1) keeps total elements and infers the -1 dimension.
- arr.T transposes 2D; arr.ravel() flattens to 1D; .astype(np.float32) converts dtype.
Building blocks and the shape ladder.
Examples
Shape vocabulary in one pass
import numpy as npz = np.zeros((2, 3)); o = np.ones((3,)); r = np.arange(12)print(z.shape, o.shape) # (2, 3) (3,)rows = np.arange(12).reshape(3, 4)flat = rows.ravel() # (12,) view of rowstx = rows.T # (4, 3)print(rows.shape, flat.shape, tx.shape)reshape reinterprets the same 12 values as a 3×4 grid; ravel flattens back to 1D without copying; .T swaps axes. Because views share memory, mutating `flat` would mutate `rows`.
In production
- An image pipeline reshapes 100k flattened pixels from (n,784) back into (n,28,28) for a CNN.
- A timeseries bearer encodes dates to a linspace-aligned index before a Forest/GBM fit.
- An estimator-dtype pipeline casts float64 to float32 before GPU transfer to halve memory.
Best practices
- Fix the target shape with `-1` (arity) to avoid counting elements by hand.
- Use np.linspace over arange for float ranges — arange's float step is subject to rounding.
- Pick dtype up front: float32 for ML features, float64 when precision matters.
Common mistakes
- np.reshape to a shape whose product doesn't match the number of elements (ValueError).
- Mutating a reshape view and silently changing the original array.
- Letting np.array infer float dtype from ints with NaN present — you get object arrays.
Debugging tips
- On reshape errors, print arr.size and arr.shape first — mismatch is always a counting problem.
- If you intended a copy, reshape a copy or use .copy() before mutating.
- Check arr.dtype when results are weird (e.g., object array from ragged input).
Interview checkpoint
Hands-on lab
- Construct filled and ranged arrays
- Reshape between (n,), (n, d), (n, c, h) with -1 inference
- Prove reshape/ravel share memory
Shape Gym: Build, Reshape, View
25 min · beginner
Quick quiz
np.linspace(0, 10, 5) produces:
reshape(-1) always produces a flat 1D copy.