The ndarray is NumPy's core data structure — a grid of values, all of the same type, with a fixed shape. Understanding shape and indexing is the single most useful NumPy skill for ML.
Creating Arrays
import numpy as np
a = np.array([1, 2, 3]) # 1D array, shape (3,)
b = np.array([[1, 2], [3, 4], [5, 6]]) # 2D array, shape (3, 2) — 3 rows, 2 columns
zeros = np.zeros((2, 3)) # 2x3 array of zeros
ones = np.ones((3, 3)) # 3x3 array of ones
rng = np.arange(0, 10, 2) # [0 2 4 6 8]
lin = np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.] — 5 evenly spaced points
Shape and dtype
X = np.array([[1200, 3], [800, 2], [1500, 4]])
print(X.shape) # (3, 2) — 3 samples, 2 features. This is the shape sklearn expects for X.
print(X.dtype) # int64 — every element is the same type; unlike Python lists
In ML code, X.shape is checked constantly — a shape mismatch between your features and what a model expects is one of the most common runtime errors, and reading the error's expected-vs-actual shape is usually enough to debug it.
Indexing and Slicing
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(X[0]) # [1 2 3] — first row
print(X[:, 0]) # [1 4 7] — first column, ALL rows
print(X[0:2, 1:3]) # [[2 3], [5 6]] — sub-matrix
print(X[X > 5]) # [6 7 8 9] — boolean/fancy indexing: all values > 5, flattened
Reshaping
flat = np.array([1, 2, 3, 4, 5, 6])
matrix = flat.reshape(2, 3) # reorganize into 2 rows, 3 columns
print(matrix)
# [[1 2 3]
# [4 5 6]]
col = np.array([1, 2, 3]).reshape(-1, 1) # common pattern: turn a 1D array into a column
print(col.shape) # (3, 1) — scikit-learn often requires this shape for a single feature
The -1 tells NumPy "figure out this dimension automatically" — reshape(-1, 1) is extremely common in ML code when scikit-learn expects a 2D array but you have a 1D one.
Practical Use Cases
- Reshaping a single feature column into the 2D shape scikit-learn requires
- Slicing out training batches, features, or specific rows/columns from a dataset
- Boolean masking to filter samples matching a condition (e.g. outlier removal)
Common Mistakes
- Passing a 1D array where scikit-learn expects a 2D array (a
ValueError: Expected 2D array, got 1D array instead) — fix with.reshape(-1, 1). - Confusing
X[0](first row of a 2D array) withX[:, 0](first column, all rows) — one of the most common indexing slips.
Interview Relevance
Q: "You get 'Expected 2D array, got 1D array instead' from scikit-learn — what's happening and how do you fix it?" scikit-learn models expect X with shape (n_samples, n_features), even for a single feature — reshape a 1D array with .reshape(-1, 1) to add the required second dimension.
Practice Question
Given a 1D NumPy array of 12 values, write the code to reshape it into a 2D array with 3 rows and 4 columns, and separately into a column vector of shape (12, 1).