Foundations#

Getting Started#

As necessary, add install numpy to your Python virtual environment

% source venv/bin/activate
% pip install numpy

For Python, the standard convention is to import NumPy as np

1import numpy as np

Creating Arrays#

NumPy provides multiple ways to create arrays.

From Lists#

One methods is to create arrays from existing Python lists. In this example, we’ll create a 1D array representing the closing prices of a stock over 5 days, and a 2D array representing 3 different stocks over the same period.

 1# 1D Array: Closing prices for Apple (AAPL)
 2aapl_prices = np.array([150.25, 152.10, 151.05, 153.40, 155.00])
 3
 4# 2D Array: Prices for [AAPL, MSFT, GOOGL] over 3 days
 5# Shape is (3, 3) -> (Rows: Stocks, Columns: Days)
 6portfolio_prices = np.array([
 7    [150.25, 152.10, 151.05],  # AAPL
 8    [305.00, 308.50, 306.20],  # MSFT
 9    [2800.10, 2805.50, 2799.00] # GOOGL
10])
11
12print(f"AAPL Array Shape: {aapl_prices.shape}")
13print(f"Portfolio Array Shape: {portfolio_prices.shape}")
AAPL Array Shape: (5,)
Portfolio Array Shape: (3, 3)

From NumPy Methods#

You can also create arrays usings Numpy’ts

1zeros = np.zeros((3, 4))       # 3x4 array of zeros
2ones = np.ones((2, 3, 4))      # 2x3x4 array of ones
3empty = np.empty((2, 3))       # Uninitialized array 
4
5identity = np.eye(4)           # Identity matrix of size 4x4 (1s on diagonal)
6
7print("Zeros Array:\n", zeros)
8# add additional print statements for ones, empty, and identity 
Zeros Array:
 [[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

Be careful when using the uninitialized array - there’s no gaurentee what will be in those memory locations - you must first write before you can read that array.

Ranges#

We can also creates arrays with ranges:

1# Arrays with ranges
2range_arr = np.arange(0, 10, 2)     # [0, 2, 4, 6, 8]
3linspace_arr = np.linspace(0, 1, 5) # 5 evenly spaced values from 0 to 1
4
5print("range_arr:", range_arr)
6print("linspace_arr:", linspace_arr)  
range_arr: [0 2 4 6 8]
linspace_arr: [0.   0.25 0.5  0.75 1.  ]

Random Values#

We can also generate NumPy arrays with random numbers. The original legacy approach was to seed the overall random number for NumPy with a specific number for reproducibility.

1np.random.seed(12345)
2random_arr = np.random.random((3, 3))
3random_int = np.random.randint(0, 100, size=(4, 4))
4print(random_arr)
[[0.92961609 0.31637555 0.18391881]
 [0.20456028 0.56772503 0.5955447 ]
 [0.96451452 0.6531771  0.74890664]]

The preferred method is to use default_rng() to create an independent generatory object, preventing potentional conflicts with other parts of your program that might also be using NumPy’s random functions - better isolation and control.

If you don’t provide a seed value, NumPy seeds the random number generator using system-provided randomness (like /dev/urandom on Unix-like systems) or, failing that, the current system time. Since the system time or other system randomness sources will likely be different each time the program runs, the generated numbers will also be different.

 1# Random arrays
 2
 3from numpy.random import default_rng
 4rng = default_rng(seed=42)  # Seed for reproducibility
 5
 6random_arr = rng.random((3, 3))
 7random_int = rng.integers(0, 100, size=(4, 4))
 8
 9print("Random Array:\n", random_arr)
10print("Random Integers:\n", random_int)
Random Array:
 [[0.77395605 0.43887844 0.85859792]
 [0.69736803 0.09417735 0.97562235]
 [0.7611397  0.78606431 0.12811363]]
Random Integers:
 [[83 45 50 37]
 [18 92 78 64]
 [40 82 54 44]
 [45 22  9 55]]

Data Types#

NumPy arrays are homogeneous: every element in an array has the same data type, called a dtype.

NumPy offers a rich set of numeric, boolean, datetime, and structured types.

Choosing the right dtype is important for:

  1. Memory usage (e.g., float32 uses half the memory of float64)

1a = np.zeros(1_000_000, dtype=np.float32)
2b = np.zeros(1_000_000, dtype=np.float64)
3
4print(a.nbytes)  # 4 MB
5print(b.nbytes)  # 8 MB
4000000
8000000
  1. Performance (smaller dtypes are often faster)

  2. Precision (financial and scientific work often needs float64)

1print(np.float32(1/3))  # ~0.33333334
2print(np.float64(1/3))  # ~0.3333333333333333
0.33333334
0.3333333333333333
  1. Interoperability (e.g., matching dtypes when loading binary data) When reading binary data or interfacing with C/Fortran code, you often must specify the exact dtype.

Check an array’s dtype#

You can check an array’s dtype with the dtype property.

1prices = np.array([150.25, 152.10, 151.05, 153.40, 155.00])
2prices.dtype
dtype('float64')

Cast an array to a different dtype#

Use the astype() method to convert the value to a different type.

1arr_float32 = prices.astype(np.float32)
2print(arr_float32.dtype, arr_float32) 
3arr_int64 = prices.astype("int64")
4print(arr_int64.dtype, arr_int64)
float32 [150.25 152.1  151.05 153.4  155.  ]
int64 [150 152 151 153 155]

Create arrays with a dtype#

As you create NumPy arrays, you can specify, the datatype.

1zero_32 = np.zeros((3, 3), dtype=np.int32)
2seq_64 = np.array([1, 2, 3], dtype=np.float64)
3print("zero_32:", zero_32.dtype)
4print("seq_64:", seq_64.dtype)
zero_32: int32
seq_64: float64

Common NumPy Data Types#

Below is a friendly list of the most widely used dtypes you’ll encounter. NumPy supports many aliases (e.g., np.int_ is usually the same as Python int), but the table sticks to the canonical names.

Category

dtype

Description

Size

Boolean

bool_

True/False values

1 byte

Signed Integers

int8

−128 to 127

1 byte

int16

−32,768 to 32,767

2 bytes

int32

Typical integer

4 bytes

int64

Large integer

8 bytes

Unsigned Integers

uint8

0 to 255

1 byte

uint16

0 to 65,535

2 bytes

uint32

0 to 4.29e9

4 bytes

uint64

0 to 1.8e19

8 bytes

Floating-Point

float16

Half precision

2 bytes

float32

Single precision

4 bytes

float64

Double precision (default)

8 bytes

float128 **

Extended precision (platform-dependent)

16 bytes

Complex

complex64

2 × float32

8 bytes

complex128

2 × float64

16 bytes

complex256 **

2 × float128

32 bytes

Strings / Bytes

bytes_

Fixed-length raw bytes

variable

str_

Fixed-length Unicode

variable

Datetime

datetime64

Dates/timestamps with units

8 bytes

Timedelta

timedelta64

Time differences

8 bytes

Object

object_

Arbitrary Python objects

pointer

Structured

custom dtype

C-style structs, records

variable

** may not be available on Windows or some CPUs.*

Choosing the Right dtype#

For numeric computing:

  • float64 for most scientific/financial data

  • float32 for memory-constrained or GPU workloads

  • int32/int64 for integer datasets

For large categorical or label data:

  • Use str_ only when needed

  • Otherwise, consider encoding categories into integers

For dates/times:

  • Use datetime64 / timedelta64 over Python datetime objects (faster + vectorized)

See 2-numpy_datatpye_pitfalls.ipynb for more concerns with datatypes.

Loading & Saving Data in NumPy#

NumPy provides several ways to read and write data, and the “best” approach depends on file format, data cleanliness, and performance needs.

NumPy’s Native Binary Formats (.npy / .npz)#

If you control the data pipeline or just need fast I/O, NumPy’s own formats are an ideal choice.

Why use .npy or .npz?

  • Fast: no parsing or text encoding overhead

  • Exact dtype preservation

  • Stores shape + metadata

  • Cross-platform + stable

When to use this:

  • Intermediate datasets in data pipelines

  • Model weights, precomputed matrices

  • Any situation needing speed + reliability

 1aapl_prices = np.array([150.25, 152.10, 151.05, 153.40, 155.00])
 2portfolio_prices = np.array([
 3    [150.25, 152.10, 151.05],  # AAPL
 4    [305.00, 308.50, 306.20],  # MSFT
 5    [2800.10, 2805.50, 2799.00] # GOOGL
 6])
 7
 8np.save("data.npy", aapl_prices)                # save a single array
 9np.savez("data.npz", aapl=aapl_prices, port=portfolio_prices)          # save multiple arrays in one file (compressed)
10np.savez_compressed("data_c.npz", x=aapl_prices)  # optional compression
1# Verify saved files and their sizes
2import os
3
4# List files starting with 'data' and show their sizes
5for filename in os.listdir('.'):
6    if filename.startswith('data') and filename.endswith(('.npy', '.npz')):
7        size = os.path.getsize(filename)
8        print(f"{filename}: {size:,} bytes")
data.npy: 168 bytes
data.npz: 614 bytes
data_c.npz: 226 bytes
 1# Load arrays back from the files
 2arr = np.load("data.npy")
 3print(arr.dtype, arr)
 4
 5print("Combined Data from data.npz:")
 6data = np.load("data.npz")
 7aapl = data["aapl"]
 8port = data["port"]
 9print(aapl.dtype, aapl)
10print(port.dtype, port)
11 
12print("Compressed Data from data_c.npz:")
13compressed_data = np.load("data_c.npz")
14x = compressed_data["x"]
15print(x.dtype, x)   
float64 [150.25 152.1  151.05 153.4  155.  ]
Combined Data from data.npz:
float64 [150.25 152.1  151.05 153.4  155.  ]
float64 [[ 150.25  152.1   151.05]
 [ 305.    308.5   306.2 ]
 [2800.1  2805.5  2799.  ]]
Compressed Data from data_c.npz:
float64 [150.25 152.1  151.05 153.4  155.  ]
1for fn in ("data.npy", "data.npz", "data_c.npz"):
2    if os.path.exists(fn):
3        os.remove(fn)
4        print(f"Deleted {fn}")
5    else:
6        print(f"File not found: {fn}")
Deleted data.npy
Deleted data.npz
Deleted data_c.npz

Clean Numeric Text Files (CSV/TSV) with np.loadtxt#

loadtxt() is perfect when your file is strictly numeric and well-structured (no missing values, every row same length).

Most likely, you will need to define parameters specifying the delimiter, the need to skip the header row, and which columns to use.

The Python code below reads adjusted stock prices. The file has the following header -

date,open,high,low,close,adjusted_close,volume,dividend_amount,split_coefficient

As the date needs to be separate type from the price data, we’ll exclude that column. Similarly, we will not use the remaining fields after the adjusted close even though they are numeric.

1# Load GS prices: skip header, skip date column 
2gs_prices = np.loadtxt(
3    "../StockData/stocks/gs.csv",
4    delimiter=",",       # Delimiter is comma
5    skiprows=1,          # Skip header row
6    usecols=range(1, 6)  # Skip date column (0), read columns 1-5. Can also be a list
7)
8print(gs_prices.shape, gs_prices.dtype)
(6554, 5) float64

When to load CSV files directly with NumPY:

  • Small to medium sized data files

  • Clean numeric grids (e.g., simulation outputs)

  • Not great for missing values (“”, “NA”)

  • Not for mixed types (dates, labels)

genfromtext() is a more complex method that can handle missing values and supports custom field convertors (e.g., strings to numbers).

Pandas for Real-World CSVs, then Convert to NumPy#

Pandas is designed for flexible text-based data ingestion, especially when CSV files contain:

  • Date/time columns

  • Labels, categories

  • Missing values

  • Many columns with mixed types

Once cleaned, a DataFrame’s columns convert cleanly to NumPy arrays for numerical work.

1import pandas as pd
2
3df = pd.read_csv("../StockData/stocks/gs.csv", parse_dates=["date"])
4print(df.info())
5prices = df["adjusted_close"].to_numpy()
6print()
7print("NumPy array:",prices.dtype,prices.shape)
<class 'pandas.DataFrame'>
RangeIndex: 6554 entries, 0 to 6553
Data columns (total 9 columns):
 #   Column             Non-Null Count  Dtype         
---  ------             --------------  -----         
 0   date               6554 non-null   datetime64[us]
 1   open               6554 non-null   float64       
 2   high               6554 non-null   float64       
 3   low                6554 non-null   float64       
 4   close              6554 non-null   float64       
 5   adjusted_close     6554 non-null   float64       
 6   volume             6554 non-null   int64         
 7   dividend_amount    6554 non-null   float64       
 8   split_coefficient  6554 non-null   float64       
dtypes: datetime64[us](1), float64(7), int64(1)
memory usage: 461.0 KB
None

NumPy array: float64 (6554,)

Why this is common:

  • Pandas handles all the messy parsing details

  • You can filter, clean, resample, merge, etc.

  • NumPy array extraction is simple and fast

When to use this:

  • Financial time series

  • ML preprocessing pipelines

  • Any CSV with non-numeric complications

File Summary#

File Type

Recommended Method

Notes

Internal intermediate data

.npy / .npz

Fast, reliable, preserves dtype

Clean CSV/TSV

np.loadtxt

Simple numeric data only

Messy CSV / Mixed types

np.genfromtxt

Handles missing values + names

Custom binary formats

np.fromfile

Must know dtype + shape

“Real-world” CSV with dates, labels

Pandas, then .to_numpy()

Most robust parsing

Best-Practice Pattern for Data Science & Finance

A common and effective pattern:

  1. Load text data with pandas (handles parsing, dates, missing values).

  2. Clean + preprocess using DataFrame operations.

  3. Convert to NumPy for heavy numeric code (vectorization, ML prep).

  4. Save intermediate results with .npy/.npz to avoid re-parsing CSV later.

This gives you the robustness of pandas and the speed of NumPy where it matters.

Indexing and Slicing#

As you’d expect from Python’s built-in indexing and slicing capabilities, NumPy provides the expected functionality.

 1arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
 2
 3# Basic indexing
 4print(arr[5])        # 5
 5print(arr[-1])       # 9 (last element)
 6
 7# Slicing
 8print(arr[2:7])      # [2 3 4 5 6]
 9print(arr[::2])      # [0 2 4 6 8] (every 2nd element)
10
11# Multi-dimensional indexing and slicing
12print("\n2D Array Indexing:")
13arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
14print("Array:\n",arr2d)
15print()
16print(arr2d[1, 2])   # 6 (row 1, column 2)
17print(arr2d[:2, 1:]) # First 2 rows, columns 1 onward
5
9
[2 3 4 5 6]
[0 2 4 6 8]

2D Array Indexing:
Array:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

6
[[2 3]
 [5 6]]

Boolean Indexing#

Boolean indexing in NumPy is a powerful way to filter, slice, and manipulate arrays using logical conditions rather than explicit indices. Instead of selecting elements by their numeric position, you create a Boolean mask—an array of True or False values—derived from a condition applied to the original array. NumPy then returns only the elements where the mask is True. This approach is efficient, expressive, and widely used in data analysis, including finance, where analysts frequently need to filter prices, returns, or indicators based on thresholds or logical rules.

 1# Daily percentage returns for a stock
 2returns = np.array([0.5, -1.2, 2.3, 0.1, -0.8, 1.5, -2.1])
 3
 4# Boolean mask for days when the stock moved more than 1% in either direction
 5large_moves_mask = np.abs(returns) > 1.0
 6
 7# Apply Boolean indexing
 8large_moves = returns[large_moves_mask]
 9
10print("Boolean mask:", large_moves_mask)
11print("Large moves:", large_moves)
Boolean mask: [False  True  True False False  True  True]
Large moves: [-1.2  2.3  1.5 -2.1]

Fancy Indexing#

Indexing with an array of indices in NumPy (often called fancy indexing) lets you select elements from an array by specifying their positions in another array, rather than using a single integer or a slice. Instead of pulling a continuous range like prices[0:5], you can pass a NumPy array or list of specific indices such as prices[[0, 2, 5]] to grab exactly those elements. This is especially useful in finance when you want to extract data for specific days (e.g., month-end dates), particular assets in a portfolio, or event dates (like Federal Reserve announcements) without looping manually. The result is a new array consisting of the values at the requested index positions, preserving order as given in the index array.

 1# Daily returns for a stock over 10 days (in %)
 2daily_returns = np.array([0.2, -0.3, 1.1, 0.5, -0.8, 2.0, -1.5, 0.4, 0.9, -0.2])
 3
 4# Suppose these are indices of important event days (e.g., earnings, Fed announcements)
 5event_day_indices = np.array([2, 5, 8])  # 3rd, 6th, and 9th trading days
 6
 7# Use array of indices (fancy indexing) to extract returns on event days
 8event_day_returns = daily_returns[event_day_indices]
 9
10print("All daily returns:", daily_returns)
11print("Event day indices:", event_day_indices)
12print("Event day returns:", event_day_returns)
All daily returns: [ 0.2 -0.3  1.1  0.5 -0.8  2.  -1.5  0.4  0.9 -0.2]
Event day indices: [2 5 8]
Event day returns: [1.1 2.  0.9]

Vectorization#

Vectorization is NumPy’s killer feature. Instead of writing Python for loops that operate on one element at a time, NumPy lets you apply operations to entire arrays at once.

The advantages:

  • Cleaner – your code looks like math, not bookkeeping, and

  • Much faster – the heavy lifting happens in optimized C loops, not in slow Python loops

  • Much less memory allocation and object reference managment

Consider this example that doubles 1,000,000 numbers:

 1import timeit
 2
 3# Without NumPy (slow)
 4python_list = list(range(1_000_000))
 5result = [x * 2 for x in python_list]
 6
 7# With NumPy (fast)
 8numpy_array = np.arange(1_000_000)
 9result = numpy_array * 2  # Vectorized, no explicit loop
10
11
12# Time the Python list approach
13python_time = timeit.timeit(
14    stmt='result = [x * 2 for x in python_list]',
15    globals={'python_list': python_list},
16    number=10
17) / 10
18
19# Time the NumPy approach
20numpy_time = timeit.timeit(
21    stmt='result = numpy_array * 2',
22    globals={'numpy_array': numpy_array},
23    number=10
24) / 10
25
26print(f"Python list approach w/ comprehension: {python_time:.6f} seconds")
27print(f"NumPy approach: {numpy_time:.6f} seconds")
28print(f"NumPy is {python_time / numpy_time:.1f}x faster")
29print("NumPy Array Type:", numpy_array.dtype)
30print("Python List Element Type:", type(python_list[0]))
Python list approach w/ comprehension: 0.024315 seconds
NumPy approach: 0.000415 seconds
NumPy is 58.6x faster
NumPy Array Type: int64
Python List Element Type: <class 'int'>

A NumPy array stores values in a contiguous block of memory with a fixed data type (dtype). The C loop can simply walk through memory and multiply each value.

A Python list, by contrast:

  • Stores references (pointers) to separate Python integer objects

  • Needs to follow each reference, multiply, possibly allocate new objects, and update references

Most arithmetic operations in NumPy are element-wise and are automatically vectorized. The NumPy Financial notebook provides more examples in the context of real-world problems.

1# Element-wise operations
2arr = np.array([1, 2, 3, 4])
3print(arr + 10)      # [11 12 13 14]
4print(arr * 2)       # [2 4 6 8]
5print(arr ** 2)      # [1 4 9 16]
[11 12 13 14]
[2 4 6 8]
[ 1  4  9 16]

Key points:

  • No explicit for loops

  • Operations are applied to each element under the hood

  • These operations are implemented as ufuncs (“universal functions”) in NumPy – functions that operate element-wise on arrays with broadcasting support.

Vectorization also works between arrays of the same shape:

1# Operations between arrays
2arr1 = np.array([1, 2, 3])
3arr2 = np.array([4, 5, 6])
4print(arr1 + arr2)   # [5 7 9]
5print(arr1 * arr2)   # [ 4 10 18]
6print(arr2 - arr1)   # [3 3 3]
[5 7 9]
[ 4 10 18]
[3 3 3]

Broadcasting#

Broadcasting allows NumPy to work with arrays of different shapes during arithmetic operations. The smaller array is “broadcast” across the larger array:

 1# Scalar broadcasting
 2arr = np.array([[1, 2, 3], [4, 5, 6]])
 3print("Scalar Broadcasting:")
 4print(arr + 10)  # Adds 10 to every element
 5
 6# 1D to 2D broadcasting
 7arr = np.array([[1, 2, 3], [4, 5, 6]])
 8row = np.array([10, 20, 30])
 9print("\nRow Broadcasting:")
10print(arr + row)  # Adds row to each row of arr
11# Result: [[11 22 33], [14 25 36]]
12
13# Column broadcasting
14print("\nColumn Broadcasting:")
15col = np.array([[10], [20]])
16print(arr + col)
17# Result: [[11 12 13], [24 25 26]]
Scalar Broadcasting:
[[11 12 13]
 [14 15 16]]

Row Broadcasting:
[[11 22 33]
 [14 25 36]]

Column Broadcasting:
[[11 12 13]
 [24 25 26]]

Broadcasting rules: Two dimensions are compatible when they are equal or one of them is 1.

Broadcasting is a huge part of vectorization: you write expressions on whole arrays, and NumPy figures out how to align shapes to perform element-wise operations.

Universal Functions#

Universal functions, or ufuncs, are the specialized functions that give NumPy its exceptional performance. A ufunc is a function that operates element-wise on NumPy arrays, performing fast vectorized operations written in compiled C code. They are called “universal” because they work uniformly across arrays of any shape through NumPy’s broadcasting rules.

When you write np.sqrt(arr) or arr1 + arr2, you’re using ufuncs.

More details are available in the ufuncs notebook.

 1arr = np.array([1, 2, 3, 4])
 2
 3# Unary ufuncs
 4print("sqrt:", np.sqrt(arr))
 5print("exp:", np.exp(arr))
 6print("log:", np.log(arr))
 7
 8# Binary ufuncs
 9arr1 = np.array([1, 2, 3])
10arr2 = np.array([4, 5, 6])
11print("add:", np.add(arr1, arr2))
12print("maximum:", np.maximum(arr1, arr2))
sqrt: [1.         1.41421356 1.73205081 2.        ]
exp: [ 2.71828183  7.3890561  20.08553692 54.59815003]
log: [0.         0.69314718 1.09861229 1.38629436]
add: [5 7 9]
maximum: [4 5 6]

NumPy Reductions#

A reduction is an operation that collapses an array down to a smaller array — or a single scalar — by combining its elements: summing them, averaging them, finding the largest, and so on. Where ufuncs like np.sqrt or np.add preserve the shape of the array (one output per input element), reductions do the opposite: they aggregate many values into fewer.

NumPy exposes most reductions two equivalent ways: as a top-level function, np.sum(arr), or as a method on the array itself, arr.sum(). Both call the same underlying code, so pick whichever reads better in context — both are idiomatic.

Some of the most common reductions:

  • sum – total of all elements

  • mean – average value

  • min / max – smallest / largest value

  • std / var – how spread out the values are

  • argmin / argmax – the index of the smallest / largest value, rather than the value itself

  • prod – product of all elements

  • cumsum – running total, kept as an array instead of collapsed to one number

1arr = np.array([2, 4, 6, 8, 10, 12])
2
3print("sum:", np.sum(arr), "|", arr.sum())    # 42
4print("mean:", np.mean(arr), "|", arr.mean()) # 7.0
5print("min:", np.min(arr), "|", arr.min())    # 2
6print("max:", np.max(arr), "|", arr.max())    # 12
sum: 42 | 42
mean: 7.0 | 7.0
min: 2 | 2
max: 12 | 12

std and var describe how spread out the values are around the mean — a small std means the values are clustered close to the mean, a large one means they’re spread out widely.

argmin and argmax work differently from the reductions above: instead of returning a value from the array, they return the index at which that value occurs. That’s useful when you care about where the extreme value is, not just what it is.

Not every reduction collapses all the way down to a single number. cumsum is a running reduction — it returns an array the same size as the input, where each element is the sum of everything up to and including that position.

1print("std:", np.std(arr), "|", arr.std())          # spread around the mean
2print("var:", np.var(arr), "|", arr.var())           # std squared
3print("argmin:", np.argmin(arr), "|", arr.argmin())  # index of the smallest value
4print("argmax:", np.argmax(arr), "|", arr.argmax())  # index of the largest value
5print("prod:", np.prod(arr), "|", arr.prod())
6print("cumsum:", np.cumsum(arr), "|", arr.cumsum())  # running total, not a single number
std: 3.415650255319866 | 3.415650255319866
var: 11.666666666666666 | 11.666666666666666
argmin: 0 | 0
argmax: 5 | 5
prod: 46080 | 46080
cumsum: [ 2  6 12 20 30 42] | [ 2  6 12 20 30 42]

Key points:

  • Reductions collapse an array into fewer values by combining elements with an aggregating operation

  • np.func(arr) and arr.func() are equivalent — use whichever reads better

  • argmin/argmax return a position, not a value; everything else above returns a value (or, for cumsum, an array of values)

So far every example has reduced a 1-D array down to a single number. But what happens when arr is 2-D? Does np.sum(matrix) add up every element, or just a row, or just a column?

The Axis Parameter#

For a 2-D array, axis tells a reduction which direction to collapse along:

  • axis=0 reduces along the first axis — it walks down each column, combining the entries from every row, and leaves one result per column

  • axis=1 reduces along the second axis — it walks across each row, combining the entries from every column, and leaves one result per row

  • leaving axis out entirely reduces over every element, just like the 1-D examples above

A helpful way to think about it: the axis you name is the one that disappears from the shape.

1matrix = np.array([[1, 2, 3, 4],
2                    [5, 6, 7, 8]])
3print("matrix:\n", matrix)
4print("shape:", matrix.shape)
5
6print("\nsum, no axis:", np.sum(matrix))        # 36 -- every element
7print("sum, axis=0:  ", np.sum(matrix, axis=0)) # column sums
8print("sum, axis=1:  ", np.sum(matrix, axis=1)) # row sums
matrix:
 [[1 2 3 4]
 [5 6 7 8]]
shape: (2, 4)

sum, no axis: 36
sum, axis=0:   [ 6  8 10 12]
sum, axis=1:   [10 26]
 1# Using a finanncial example: rows are days, columns are stocks(assets)
 2returns = np.array([
 3    [0.01,  0.02, -0.01],
 4    [0.03, -0.02,  0.00],
 5    [-0.01, 0.01,  0.02],
 6]) 
 7
 8stock_mean_returns = returns.mean(axis=0)  # Mean return for each stock (column-wise)
 9day_mean_returns = returns.mean(axis=1)  # Mean return for each day (row-wise)
10print("Mean returns for each stock:", stock_mean_returns)
11print("Mean returns for each day:", day_mean_returns)
Mean returns for each stock: [0.01       0.00333333 0.00333333]
Mean returns for each day: [0.00666667 0.00333333 0.00666667]

Notice the shapes: matrix is (2, 4), the axis=0 result has shape (4,), and the axis=1 result has shape (2,). Reducing along an axis removes that axis from the shape entirely — a 2-D array becomes 1-D, a 1-D array becomes a scalar. The same logic applies to mean, max, and every other reduction from the previous section:

1print("mean, no axis:", np.mean(matrix))
2print("mean, axis=0: ", np.mean(matrix, axis=0))
3print("mean, axis=1: ", np.mean(matrix, axis=1))
4
5print("\nmax, axis=0:", np.max(matrix, axis=0))
6print("max, axis=1:", np.max(matrix, axis=1))
mean, no axis: 4.5
mean, axis=0:  [3. 4. 5. 6.]
mean, axis=1:  [2.5 6.5]

max, axis=0: [5 6 7 8]
max, axis=1: [4 8]

If you need the reduced axis to stick around as a size-1 dimension instead of disappearing — useful when you want the result to broadcast cleanly back against the original array — pass keepdims=True:

1print(np.sum(matrix, axis=1, keepdims=True))
2print(np.sum(matrix, axis=1, keepdims=True).shape)
[[10]
 [26]]
(2, 1)

Reshaping#

reshape reinterprets the same underlying data with a new shape:

1arr = np.arange(12)
2print(arr)
3print(arr.reshape(3, 4))    # 3x4 array
4print(arr.reshape(2, 2, 3)) # 2x2x3 array
[ 0  1  2  3  4  5  6  7  8  9 10 11]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]]

Key idea: no elements are created or destroyed, and their order in memory is unchanged (unless you play with the order argument). reshape just changes how NumPy indexes into that same 1D block of numbers.

For a.reshape(new_shape) to work, the product of dimensions in new_shape must equal a.size.

1a = np.arange(12)
2
3a.reshape(4, 3)   # OK: 4 * 3 = 12
4a.reshape(2, 2, 3)  # OK: 2 * 2 * 3 = 12
5
6# The following line will raise a ValueError
7# a.reshape(5, 3)   # ValueError: 5 * 3 = 15 ≠ 12
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

if a.reshape(5, 3) was executed, here’s the assocatied ValueError:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[44], line 6
      3 a.reshape(4, 3)   # OK: 4 * 3 = 12
      4 a.reshape(2, 2, 3)  # OK: 2 * 2 * 3 = 12
----> 6 a.reshape(5, 3)   # ValueError: 5 * 3 = 15 ≠ 12

ValueError: cannot reshape array of size 12 into shape (5,3)

You can set one of the dimensions to -1 and NumPy will calculate (infer) that dimension

1# Automatic dimension inference
2print(arr.reshape(3, -1))   # 3 rows, columns inferred
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

You can call flatten multi-dimensional arrays into single dimension.

1# Flattening
2arr2d = np.array([[1, 2], [3, 4]])
3print(arr2d.flatten())      # [1 2 3 4]
4print(arr2d.ravel())        # Same, but may return a view
[1 2 3 4]
[1 2 3 4]

Printing Matrices#

Most of the time, you can simply use print() with a NumPy array:

1prices = np.array([[150.25, 152.10, 151.05],
2                   [305.00, 308.50, 306.20]])
3
4print(prices)
[[150.25 152.1  151.05]
 [305.   308.5  306.2 ]]

For quick debugging this is fine, but in data science and finance you often want:

  • Fixed decimal places (e.g., 4 decimals)

  • Suppress scientific notation

  • Nicer wrapping / indentation for multi-line arrays

NumPy gives you a few options.

Setting global print options#

np.set_printoptions lets you control how all arrays are printed in that Python session.

1np.set_printoptions(precision=4,    # 4 decimal places
2                    linewidth=120,  # wider line width
3                    suppress=True)  # avoid scientific notation for small numbers
4
5A = np.random.random((3, 7))
6print(A)
[[0.7237 0.6425 0.7175 0.4676 0.3256 0.4396 0.7297]
 [0.994  0.6769 0.7908 0.1709 0.0268 0.8004 0.9037]
 [0.0247 0.4917 0.5263 0.5964 0.052  0.8951 0.7283]]

This is useful in a notebook when you want a consistent display format for many arrays.

np.set_printoptions(**np.get_printoptions()) will reset back to the default.

One-off formatting (without changing globals)#

If you only want special formatting for one array, use np.array2string. You can control both the number formatting and the indentation of wrapped lines.

 1np.set_printoptions(**np.get_printoptions()) # Reset to default settings
 2
 3A = np.arange(9).reshape(3, 3) / 7.0
 4
 5formatted = np.array2string(
 6    A,
 7    precision=4,              # 4 decimal places
 8    suppress_small=True,      # avoid scientific notation
 9    prefix="    "             # indent wrapped lines. (usually leave this off)
10)
11
12print(formatted)
[[0.     0.1429 0.2857]
     [0.4286 0.5714 0.7143]
     [0.8571 1.     1.1429]]

The prefix argument tells NumPy what to put in front of every line after the first, so this is a convenient way to indent multi-line arrays.

If you like, you can combine this with a global style:

1np.set_printoptions(precision=4, suppress=True)
2print(np.array2string(A, prefix=" "))
[[0.     0.1429 0.2857]
  [0.4286 0.5714 0.7143]
  [0.8571 1.     1.1429]]

Full control with Python string formatting#

Sometimes you want to decide exactly how each value is printed (for example, for aligned columns or CSV-like output). You can always loop over the rows and use f-strings:

1import numpy as np
2
3A = np.random.random((3, 3))
4
5for row in A:
6    print("  ".join(f"{x:0.4f}" for x in row))
0.8184  0.5002  0.8102
0.0960  0.2190  0.2587
0.4681  0.4594  0.7095

This approach gives you complete control (number of decimals, separators, alignment) and works well when you need to copy/paste results into a report or spreadsheet.

Summary#

To make the most of NumPy, start developing a mental model to “think in arrays”:

  • Replace “loop over elements” thinking with “operate on the whole array”

  • Use:

    • Element-wise ops (+, -, *, /, **)

    • Ufuncs (np.sqrt, np.exp, np.log, etc.)

    • Broadcasting

    • Boolean masking

  • Avoid manual Python loops over array elements as much as possible

Once you get used to this style, your code becomes shorter, clearer, and much faster.

This mindset will also carrry over to Pandas as well as database queries in SQL.