Python & Data Science

Numpy Array Cheat Sheet The Operations You Ll Actu

Introduction: Why This Isn’t Another 50-Page Reference Manual

You’ve probably done this before: you open the official NumPy docs, scroll for thirty seconds, see a wall of function signatures, and close the tab. You don’t need a 50-page reference manual. You need the 20% of operations that handle 90% of real-world data tasks, explained in plain English, with the common gotchas called out before they bite you.

Most NumPy cheat sheets fall into one of two traps. They’re either too terse — just syntax with no explanation — or they’re too long, trying to document every function in the library. This article bridges that gap. Every operation here includes a one-sentence plain-English translation of what it actually does and a note on the most common mistake people make with it.

This is structured as a reference you can bookmark and search, not a linear tutorial. Each part stands alone — jump straight to indexing if that’s what you need today. But scattered throughout are three dedicated callout boxes for the concepts that cause the majority of NumPy bugs: views vs. copies when slicing, the broadcasting rules, and what the axis parameter actually means. If you internalize just those three things, you’ll eliminate most of the silent errors that make NumPy feel unpredictable.

Let’s start with the raw material: creating arrays.

Part 1: Creating Arrays — Your Raw Material

Array creation is the first thing you do in any NumPy script, and the default behaviors around data type and memory layout are easy to get wrong. This section groups creation functions by what you’re actually trying to do: “I know the exact values,” “I want zeros or ones,” “I want a range,” or “I want random data.”

From a Python list: np.array()

This is the workhorse. You feed it a Python list (or list of lists), and it returns a NumPy array. The data type is inferred from the input — and this is where the first gotcha lives. If your list contains only integers, you get int64. But if even a single element is a float, the entire array becomes float64. That silent type coercion can surprise you when you later try to do integer-only operations.

import numpy as np

# All integers -> int64
int_arr = np.array([1, 2, 3, 4])
print(f"All ints: {int_arr.dtype}")  # int64

# One float poisons the whole array
mixed_arr = np.array([1, 2, 3.0, 4])
print(f"One float: {mixed_arr.dtype}")  # float64

Zeros and ones: np.zeros(shape) and np.ones(shape)

When you need a placeholder array — for initializing accumulators or creating masks — these are your tools. The critical gotcha: the default data type is float64, NOT integer. If you expect integer zeros, you must set the dtype parameter explicitly.

import numpy as np

# Default is float64 — not int!
z = np.zeros((2, 3))
print(f"zeros dtype: {z.dtype}")  # float64
print(z)
# [[0. 0. 0.]
#  [0. 0. 0.]]

# Fix: specify dtype
z_int = np.zeros((2, 3), dtype=np.int32)
print(f"zeros with dtype=int32:\n{z_int}")

Ranges: np.arange() and np.linspace()

np.arange(start, stop, step) works like Python’s built-in range() but returns an array. It’s convenient, but there’s a trap: floating-point step sizes can produce an unpredictable number of elements due to rounding. When you need an exact number of evenly-spaced points — for plotting, for instance — reach for np.linspace(start, stop, num) instead. It guarantees exactly num points and includes the endpoint by default.

import numpy as np

# arange: you specify the step size
arr_step = np.arange(0, 1, 0.25)
print(f"arange: {arr_step}")  # [0.   0.25 0.5  0.75]

# linspace: you specify the number of points
arr_lin = np.linspace(0, 1, 5)
print(f"linspace: {arr_lin}")  # [0.   0.25 0.5  0.75 1.  ]

Random data: the modern Generator API

NumPy’s random module got a major overhaul. The old way — np.random.random() — still works but is no longer recommended. The modern approach uses a Generator object created from np.random.default_rng(). This gives you better statistical properties and explicit control over seeding for reproducibility.

import numpy as np

# Modern Generator API
rng = np.random.default_rng(seed=42)
random_arr = rng.random((3, 2))  # uniform over [0, 1)
print(f"Random array (3x2):\n{random_arr}")

Special matrices: np.eye() and np.diag()

np.eye(N) gives you an N-by-N identity matrix — ones on the diagonal, zeros elsewhere. np.diag() works in two directions: feed it a 1D array to construct a diagonal matrix, or feed it a 2D array to extract the diagonal as a 1D array.

import numpy as np

# Identity matrix
I = np.eye(3)
print(f"Identity:\n{I}")

# Construct diagonal from 1D
d = np.diag([1, 2, 3])
print(f"Diagonal matrix:\n{d}")

# Extract diagonal from 2D
extracted = np.diag(d)
print(f"Extracted diagonal: {extracted}")  # [1 2 3]

Loading from files: np.loadtxt() and np.genfromtxt()

For quick-and-dirty CSV loading, np.loadtxt() works fine. If your data has missing values, np.genfromtxt() handles them more gracefully. But here’s the honest truth: for serious data loading, you want pandas. NumPy’s file-loading functions are a stopgap, not a data pipeline.

import numpy as np
from io import StringIO

# Simulate a CSV file
csv_data = StringIO("1,2,3\n4,5,6\n7,8,9")
loaded = np.loadtxt(csv_data, delimiter=",")
print(f"Loaded from CSV:\n{loaded}")

Part 2: Inspecting What You Have — Shape, dtype, and Basic Properties

Before you can manipulate an array, you need to know what you’re working with. These are the attributes you’ll actually check in a debugging session — the ones you’ll type into a print statement when something doesn’t look right.

import numpy as np

arr = np.array([[1, 2, 3, 4],
                [5, 6, 7, 8],
                [9, 10, 11, 12]], dtype=np.float64)

print(f"shape:  {arr.shape}")   # (3, 4) — 3 rows, 4 columns
print(f"ndim:   {arr.ndim}")    # 2 — a 2D array (matrix)
print(f"size:   {arr.size}")    # 12 — total number of elements
print(f"dtype:  {arr.dtype}")   # float64 — data type of elements
print(f"itemsize: {arr.itemsize}")  # 8 — bytes per element (float64 = 8 bytes)

In plain English: this array has 3 rows and 4 columns, it’s two-dimensional, it contains 12 total elements, each element is a 64-bit float, and each float takes up 8 bytes of memory.

Here’s the catch with dtype: you might be tempted to change it by assigning directly — arr.dtype = np.float32. Don’t do that. It reinterprets the raw bytes in memory without converting the values, which produces garbage. Use arr.astype(np.float32) instead — that actually converts the numbers.

import numpy as np

arr = np.array([1, 2, 3], dtype=np.float64)
print(f"Original dtype: {arr.dtype}")  # float64

# Correct way to convert
arr32 = arr.astype(np.float32)
print(f"Converted dtype: {arr32.dtype}")  # float32
print(f"Values intact: {arr32}")  # [1. 2. 3.]

Part 3: Indexing and Slicing — Getting at Your Data

Indexing is where NumPy’s power lives, but it’s also where the view-vs-copy distinction causes silent bugs. This section covers the three indexing modes and explicitly flags which returns a view and which returns a copy.

Basic slicing: returns a VIEW

Basic slicing uses the familiar start:stop:step syntax, comma-separated across dimensions. It works like Python list slicing but across multiple axes. The critical thing to remember: basic slicing returns a view — a new array object that points to the same data buffer as the original. Mutate the slice, and you mutate the original. This is the #1 source of hard-to-find bugs in NumPy code.

import numpy as np

original = np.array([[10, 20, 30, 40],
                     [50, 60, 70, 80],
                     [90, 100, 110, 120]])

# Basic slice — returns a VIEW
sliced = original[0:2, 1:3]  # rows 0-1, cols 1-2
print(f"Slice:\n{sliced}")
# [[20 30]
#  [60 70]]

# Mutate the slice — the original changes!
sliced[0, 0] = 999
print(f"Original after slice mutation:\n{original}")
# [[ 10 999  30  40]
#  [ 50  60  70  80]
#  [ 90 100 110 120]]

# Verify: they share memory
print(f"Shares memory? {np.shares_memory(original, sliced)}")  # True

Fancy indexing: returns a COPY

Fancy indexing means passing arrays of indices — like arr[[0, 2, 4]] to select specific rows. This returns a copy — a completely independent array. Mutate it freely; the original is safe.

import numpy as np

original = np.array([10, 20, 30, 40, 50])

# Fancy indexing — returns a COPY
selected = original[[0, 2, 4]]
print(f"Selected: {selected}")  # [10 30 50]

# Mutate the copy — original is unchanged
selected[0] = 999
print(f"Original unchanged: {original}")  # [10 20 30 40 50]
print(f"Copy changed: {selected}")        # [999  30  50]

print(f"Shares memory? {np.shares_memory(original, selected)}")  # False

Boolean indexing: also returns a COPY

Boolean indexing lets you select elements based on a condition. It also returns a copy. There’s a common pattern worth memorizing: arr[arr > threshold] = 0 to clip values. This works because the assignment happens on the original array through the boolean mask — the mask itself is temporary.

import numpy as np

arr = np.array([1, -2, 3, -4, 5])

# Boolean mask
mask = arr > 0
print(f"Mask: {mask}")  # [ True False  True False  True]

# Boolean indexing — returns a COPY
positives = arr[mask]
print(f"Positives: {positives}")  # [1 3 5]

# Common pattern: clip negative values to zero
arr[arr < 0] = 0
print(f"After clipping: {arr}")  # [1 0 3 0 5]

Ellipsis and np.ix_()

The ellipsis (...) means “as many colons as needed to fill the remaining dimensions.” It’s a lifesaver when you’re working with high-dimensional arrays and only care about one axis. np.ix_() is the clean way to select a subgrid from row and column index arrays in one step.

import numpy as np

# 3D array: shape (2, 3, 4)
arr_3d = np.arange(24).reshape(2, 3, 4)

# Ellipsis: select first element along last axis, regardless of ndim
first_last = arr_3d[..., 0]
print(f"Shape with ellipsis: {first_last.shape}")  # (2, 3)
print(f"Values:\n{first_last}")

# np.ix_: select a subgrid from row and column indices
arr_2d = np.arange(20).reshape(4, 5)
subgrid = arr_2d[np.ix_([0, 2], [1, 3])]
print(f"Subgrid (rows 0,2; cols 1,3):\n{subgrid}")
# [[ 1  3]
#  [11 13]]

Part 4: Shape Manipulation — Reshaping, Flattening, and Transposing

Real-world data rarely arrives in the shape your model expects. This section covers the operations that change an array’s shape without changing its data — and flags when you get a view vs. a copy.

reshape(): the shape-shifter

arr.reshape(new_shape) returns a view if possible, a copy if not (for example, when the array’s memory layout is non-contiguous). The magic trick: use -1 to let NumPy infer one dimension. arr.reshape(-1, 3) means “whatever number of rows is needed to have exactly 3 columns.”

import numpy as np

arr = np.arange(12)  # 1D: shape (12,)
print(f"Original shape: {arr.shape}")

# Reshape to 3x4
reshaped = arr.reshape(3, 4)
print(f"Reshaped (3,4):\n{reshaped}")

# -1 magic: "make it 3 columns, figure out the rows"
auto = arr.reshape(-1, 3)
print(f"Auto rows, 3 cols: shape {auto.shape}")
print(auto)

# Is it a view? Usually yes for contiguous arrays
print(f"Shares memory? {np.shares_memory(arr, reshaped)}")  # True

Flattening: ravel() vs. flatten()

Both turn a multi-dimensional array into 1D. The difference: ravel() returns a view when possible (faster, but mutations affect the original), while flatten() always returns a copy (safer, but uses more memory). Know which one you want.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

# ravel: returns a VIEW when possible
flat_view = arr.ravel()
flat_view[0] = 999
print(f"Original after ravel mutation:\n{arr}")
# [[999   2   3]
#  [  4   5   6]]

# Reset and use flatten: always a COPY
arr = np.array([[1, 2, 3], [4, 5, 6]])
flat_copy = arr.flatten()
flat_copy[0] = 999
print(f"Original after flatten mutation (unchanged):\n{arr}")
# [[1 2 3]
#  [4 5 6]]

Transpose, newaxis, and stacking

.T swaps axes. For 1D arrays, it does nothing — use .reshape(-1, 1) or np.newaxis to turn a row vector into a column vector. np.newaxis increases the number of dimensions by 1, which is essential for making broadcasting work (more on that in Part 6).

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"Original shape: {arr.shape}")  # (2, 3)
print(f"Transpose shape: {arr.T.shape}")  # (3, 2)

# 1D array: .T does nothing
vec = np.array([1, 2, 3])
print(f"1D transpose shape: {vec.T.shape}")  # still (3,)

# Convert to column vector with newaxis
col_vec = vec[:, np.newaxis]
print(f"Column vector shape: {col_vec.shape}")  # (3, 1)
print(col_vec)

# Stacking: vstack and hstack
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(f"vstack:\n{np.vstack([a, b])}")  # 2x3
print(f"hstack: {np.hstack([a, b])}")   # 1x6

Part 5: Math and Aggregation — The Operations You’ll Actually Run

This is where vectorization pays off: element-wise arithmetic, universal functions (ufuncs), and aggregations along axes. The axis parameter is the single most-confused concept in NumPy — we’ll tackle it head-on.

Element-wise arithmetic and matrix multiplication

+, -, *, /, ** all operate element by element. A * B is NOT matrix multiplication — it multiplies corresponding elements. For actual matrix multiplication, use A @ B or A.dot(B).

import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Element-wise multiplication
print(f"Element-wise A * B:\n{A * B}")
# [[ 5 12]
#  [21 32]]

# Matrix multiplication
print(f"Matrix product A @ B:\n{A @ B}")
# [[19 22]
#  [43 50]]

Universal functions (ufuncs): fast element-wise operations

np.sqrt(), np.exp(), np.log(), np.sin() — these apply to every element in the array. They’re dramatically faster than Python loops because the loop happens in compiled C code under the hood.

import numpy as np
import time

arr = np.arange(1, 1_000_000)

# Vectorized ufunc
start = time.time()
result_vec = np.sqrt(arr)
vec_time = time.time() - start

# Python loop (for comparison — don't actually do this)
start = time.time()
result_loop = [x ** 0.5 for x in range(1, 1_000_000)]
loop_time = time.time() - start

print(f"Vectorized sqrt: {vec_time:.4f} seconds")
print(f"Python loop:     {loop_time:.4f} seconds")
print(f"Speedup: {loop_time / vec_time:.0f}x")

Aggregations and the axis parameter

.sum(), .mean(), .min(), .max(), .std(), .var() — they all take an axis parameter. This is the hardest part of NumPy for most people, so let’s make it concrete.

THE AXIS RULE (plain English): The axis you specify is the one that gets eliminated. On a 2D array of shape (3, 4):

  • axis=0 means “operate down the columns — collapse the rows.” Result shape: (4,).
  • axis=1 means “operate across the rows — collapse the columns.” Result shape: (3,).

Think of it this way: axis=0 is the row axis. When you sum along axis=0, you’re summing each column independently, squashing all the rows into one row. What’s left is one value per column.

import numpy as np

arr = np.array([[1, 2, 3, 4],
                [5, 6, 7, 8],
                [9, 10, 11, 12]])

print(f"Array shape: {arr.shape}")  # (3, 4)
print(f"Array:\n{arr}")

# axis=0: collapse rows — one value per column
sum_axis0 = arr.sum(axis=0)
print(f"\nsum(axis=0) shape: {sum_axis0.shape}")  # (4,)
print(f"sum(axis=0): {sum_axis0}")
# [15 18 21 24]  — column totals

# axis=1: collapse columns — one value per row
sum_axis1 = arr.sum(axis=1)
print(f"\nsum(axis=1) shape: {sum_axis1.shape}")  # (3,)
print(f"sum(axis=1): {sum_axis1}")
# [10 26 42]  — row totals

Cumulative operations and in-place math

np.cumsum() and np.cumprod() give you running totals along an axis. In-place operations like arr += 1 modify the array directly without making a copy — faster, but dangerous if you’re sharing views.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(f"Cumulative sum: {np.cumsum(arr)}")  # [ 1  3  6 10 15]

# In-place: modifies the array directly
arr += 10
print(f"After in-place += 10: {arr}")  # [11 12 13 14 15]

Part 6: Broadcasting — The Rules That Make Shapes Compatible

Broadcasting is what lets you add a 1D array to a 2D array without writing a loop. It’s powerful, but the exact rules are non-obvious. Let’s build the intuition first.

Imagine you have a matrix of shape (4, 3) — four rows, three columns. You want to add a 1D array of shape (3,) to every row. NumPy doesn’t actually copy that 1D array four times in memory. Instead, it stretches it conceptually along the missing dimension, treating it as if it were shape (1, 3) and then (4, 3). This happens under the hood with zero memory overhead.

Now here’s the exact rule.

BROADCASTING RULE (dedicated callout box): Compare shapes from the rightmost dimension leftward. Two dimensions are compatible if they’re equal, or if one of them is 1. Missing dimensions are treated as size 1. If any dimension pair is incompatible, you get a ValueError.

Example that works: (4, 3) + (3,)

import numpy as np

# Matrix: shape (4, 3)
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9],
                   [10, 11, 12]])

# Vector: shape (3,)
vector = np.array([10, 20, 30])

# Broadcasting: (4, 3) + (3,) -> (4, 3)
# The (3,) is treated as (1, 3), then stretched to (4, 3)
result = matrix + vector
print(f"Result shape: {result.shape}")  # (4, 3)
print(result)
# [[11 22 33]
#  [14 25 36]
#  [17 28 39]
#  [20 31 42]]

What’s actually going on here? The shapes are (4, 3) and (3,). Align from the right: the rightmost dimensions are 3 and 3 — compatible. The (3,) array has no left dimension, which is treated as 1. The left dimensions are 4 and 1 — compatible because one is 1. The (3,) array is stretched along the row axis to match the 4 rows.

Example that fails: (4, 3) + (4,)

import numpy as np

matrix = np.ones((4, 3))
vector = np.array([10, 20, 30, 40])  # shape (4,)

try:
    result = matrix + vector
except ValueError as e:
    print(f"ValueError: {e}")
    # operands could not be broadcast together with shapes (4,3) (4,)

Why does this fail? Align from the right: (4, 3) vs. (4,). The rightmost dimensions are 3 and 4 — not equal, and neither is 1. Incompatible. NumPy can’t stretch either to match.

The fix: add a new axis

import numpy as np

matrix = np.ones((4, 3))
vector = np.array([10, 20, 30, 40])  # shape (4,)

# Fix: reshape (4,) to (4, 1) using np.newaxis
vector_col = vector[:, np.newaxis]  # shape (4, 1)
result = matrix + vector_col
print(f"Fixed result shape: {result.shape}")  # (4, 3)
print(result)
# [[11. 11. 11.]
#  [21. 21. 21.]
#  [31. 31. 31.]
#  [41. 41. 41.]]

Now the shapes are (4, 3) and (4, 1). Align from the right: 3 and 1 — compatible (one is 1). Then 4 and 4 — compatible. The column vector is stretched across the columns, and each row gets its own value.

Common use case: centering data

Subtracting the column mean from each column is a one-liner thanks to broadcasting.

import numpy as np

data = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]], dtype=float)

col_means = data.mean(axis=0)  # shape (3,)
centered = data - col_means     # (3, 3) - (3,) -> (3, 3)
print(f"Column means: {col_means}")
print(f"Centered data:\n{centered}")
print(f"Verify means ~0: {centered.mean(axis=0)}")

Part 7: Views vs. Copies — The Silent Bug Factory

We’ve flagged the view-vs-copy distinction throughout this article. Now let’s consolidate it into one definitive reference. This is the hardest part of NumPy to internalize, but once you know the three tiers, you’ll stop being surprised.

The three tiers of copy semantics

  1. Reference: b = a — a new name for the exact same object. Mutate b, and a changes because they’re the same thing.
  2. View: b = a.view() or b = a[:] — a different array object that shares the same data buffer. Mutate b’s elements, and a’s elements change too.
  3. Copy: b = a.copy() — completely independent data. Mutate freely.
import numpy as np

a = np.array([1, 2, 3])

# Tier 1: Reference
b_ref = a
b_ref[0] = 999
print(f"a after reference mutation: {a}")  # [999   2   3]

# Reset
a = np.array([1, 2, 3])

# Tier 2: View
b_view = a.view()
b_view[0] = 888
print(f"a after view mutation: {a}")  # [888   2   3]
print(f"Shares memory? {np.shares_memory(a, b_view)}")  # True

# Tier 3: Copy
a = np.array([1, 2, 3])
b_copy = a.copy()
b_copy[0] = 777
print(f"a after copy mutation: {a}")  # [1 2 3] — unchanged
print(f"Shares memory? {np.shares_memory(a, b_copy)}")  # False

The rules for which operations return views vs. copies

  • Basic slicing (arr[1:5], arr[:, :3]) returns a view.
  • Fancy indexing (arr[[0, 2]]) returns a copy.
  • Boolean indexing (arr[arr > 0]) returns a copy.
  • reshape() returns a view if possible, copy if not.
  • ravel() returns a view if possible; flatten() always returns a copy.

The memory-retention gotcha

Here’s a scenario that bites people in production: you take a small slice of a huge array, and then you’re done with the huge array. But the huge array stays in memory because the slice — a view — holds a reference to the original data buffer.

import numpy as np

# Create a large array
large = np.ones((10_000, 10_000))  # ~800 MB

# Take a small slice — this is a VIEW
small_slice = large[0:10, 0:10]

# Even if we delete the name 'large', the memory isn't freed
# because small_slice still references the buffer
print(f"Small slice base is large? {small_slice.base is large}")  # True

# Fix: force a copy to release the large array's memory
small_copy = large[0:10, 0:10].copy()
print(f"Copy base is None? {small_copy.base is None}")  # True — independent

How to check what you have

  • np.shares_memory(a, b) — returns True if the arrays share a data buffer.
  • b.base is a — returns True if b is a view of a.
  • b.base is None — means b owns its own data (not a view).

When in doubt after slicing out a small subset for further processing, call .copy() to release the memory of the original large array. It’s a cheap insurance policy against memory bloat.

Recap: The 20% of NumPy You’ll Use 90% of the Time

Here’s the dense summary, organized by what you’re trying to do — not by function name. Screenshot this, print it, bookmark it.

I want to…I use…Watch out for…
Create from a listnp.array([1, 2, 3])One float makes the whole array float64
Create zeros/onesnp.zeros((2,3)), np.ones((2,3))Default dtype is float64 — use dtype=int if needed
Create a rangenp.arange(0, 1, 0.1)Floating steps → unpredictable length; use linspace for exact count
Create evenly spaced pointsnp.linspace(0, 1, 100)Endpoint included by default
Create random datarng = np.random.default_rng(42); rng.random((3,2))Use the Generator API, not legacy np.random.random()
Check shape/dtypearr.shape, arr.dtype, arr.ndim, arr.sizearr.dtype = x reinterprets bytes; use .astype()
Slice rows/columnsarr[0:5, 1:3]Returns a view — mutating it changes the original
Select specific rowsarr[[0, 2, 4]]Returns a copy — safe to mutate
Filter by conditionarr[arr > 0]Returns a copy; arr[arr < 0] = 0 clips in place
Reshapearr.reshape(3, -1)-1 infers one dimension; returns view if possible
Flatten to 1Darr.ravel() (view) or arr.flatten() (copy)Know which one you need
Transposearr.TDoes nothing on 1D arrays
Add a dimensionarr[:, np.newaxis]Essential for broadcasting
Element-wise math+, -, *, /, **A * B is NOT matrix multiplication
Matrix multiplicationA @ B or A.dot(B)Shapes must align: (m,n) @ (n,p) → (m,p)
Apply function to all elementsnp.sqrt(arr), np.exp(arr)Much faster than Python loops
Sum/mean along axisarr.sum(axis=0), arr.mean(axis=1)The axis you specify gets eliminated
Broadcast arraysLet NumPy align shapes right-to-leftAdd np.newaxis to make shapes compatible
Check view vs. copynp.shares_memory(a, b), b.base is aForce a copy with .copy() to release memory

Check Your Understanding

Remember: What’s the difference between np.arange(0, 1, 0.3) and np.linspace(0, 1, 4)? Which one guarantees exactly 4 elements?

Understand: In your own words, explain why arr[0:2, 0:2] = 0 modifies the original array but arr[arr > 5] = 0 also modifies the original array — even though boolean indexing returns a copy. What’s the difference in how the assignment works?

Apply: You have a 2D array of shape (100, 5) representing 100 samples with 5 features. Write one line of NumPy that subtracts the mean of each feature (column) from every sample in that column.

Analyze: A colleague writes row_means = data.mean(axis=0) and then tries to subtract those means from each row with data - row_means. The shapes are (100, 5) and (5,). Does this broadcast correctly? Why or why not? What if they had written data.mean(axis=1) instead — what shape would that produce, and would that broadcast against (100, 5)?

Evaluate: You’re debugging a memory leak. You load a 2 GB array, take a 1 MB slice, and then delete the original array variable — but memory usage doesn’t drop. What’s the most likely cause, and what one-line fix would you apply at the slicing step?

Create: Write a function normalize_columns(arr) that takes a 2D array and returns a new array where each column has been scaled to the range [0, 1] — that is, for each column, subtract the column minimum and divide by the column range (max minus min). Use only NumPy operations (no loops). Test it on a (4, 3) array of random floats.

Apply What You Learned

Take any 2D NumPy array with at least 3 columns and 100 rows (generate one with `np.random.default_rng()`). Write a function that standardizes each column to have mean 0 and standard deviation 1 — the classic z-score normalization — using only vectorized NumPy operations. Then write a second function that does min-max scaling to [0, 1] for each column. For both functions, verify your output by checking that each column’s mean/std (or min/max) match what you expect. The deliverable is a single self-contained Python script with both functions and the verification code.

Self-check rubric:

  • Your z-score function uses .mean(axis=0) and .std(axis=0) — no Python loops.
  • Your min-max function uses .min(axis=0) and .max(axis=0) — no Python loops.
  • Broadcasting handles the shape mismatch between the (n_cols,) statistics and the (n_rows, n_cols) array.
  • Verification prints the column means and standard deviations after z-scoring (should be ~0 and ~1) and the column min/max after min-max scaling (should be 0 and 1).
  • Python Engineering Under review

    Gpu Reference For Data Scientists When You Actuall

    Before we talk about which GPU, we need to be honest about whether your workflow actually benefits from one. Most data scientists don’t need a GPU for their daily work.

  • Python Engineering Under review

    Reinforcement Learning Algorithms Reference Which

    Before we name a single algorithm, we need to name the axes that separate them. Otherwise, you’re memorizing names without knowing why they differ—like learning the names of every screwdriver without knowing whether your screw is flathead or Phillips. Let’s fix that.

  • Python Engineering Under review

    Data Visualization Libraries Reference Matplotlib

    Before we compare APIs, we need to talk about something most tutorials skip entirely: **what happens when you call `.show()`?**

  • Python Engineering Under review

    Sqlite For Data Science A Zero Setup Database For

    Think of SQLite not as a replacement for PostgreSQL or MySQL, but as a replacement for `fopen()`. That's the framing from the official SQLite documentation. You don't install a database server — you just open a file.

Looking for something else?

Search every article by title, summary or topic.