1. ndarray: NumPy core data structure
At the core of NumPy is ndarray (N-dimensional Array), which is used to store and compute multidimensional, often homogeneous data.
Compared with Python List, the main features of the NumPy array are:
- Homogeneous dtype: Array elements usually adopt a unified data type.
- Contiguous / Strided Memory: Manage data via memory buffers and Strides.
- Vectorization: Mathematical operations can be performed directly on the entire array.
- Broadcasting: Compatible with array operations of different Shape.
- multi-dimensional array: supports matrix and higher dimensions Tensor.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[1, 2, 3], [4, 5, 6]])
a.shape # (3,)
b.shape # (2, 3)
b.ndim # 2
b.size # 6
b.dtype # dtype('int64'), depending on the platform
b.nbytes # Number of bytes occupied by the array data buffer
Common array creation methods
np.array([1, 2, 3])
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5) # Generate 5 numbers evenly
np.zeros((3, 4))
np.ones((3, 4))
np.full((3, 4), 7)
np.eye(3) # Identity matrix
np.empty((3, 4)) # Not initialized, content undefined
If you need to create an array with the same Shape as an existing array:
np.zeros_like(b)
np.ones_like(b)
np.full_like(b, 5)
2. dtype: Data type and memory
NumPy common data types:
| dtype | size of each element | Common uses |
|---|---|---|
int32 | 4 Bytes | integer data |
int64 | 8 Bytes | large range integer |
float32 | 4 Bytes | Machine learning, numerical computing |
float64 | 8 Bytes | General purpose floating point calculations |
bool | Usually 1 Byte | condition mask |
a = np.array([1, 2, 3], dtype=np.float32)
a.dtype
a.astype(np.float64)
dtype and memory usage
Assume there are 1 million floating point numbers:
a = np.ones(1_000_000, dtype=np.float64)
b = a.astype(np.float32)
a.nbytes # 8,000,000
b.nbytes # 4,000,000
float32 typically takes up half the memory of float64, but is also less precise.
Note: astype() creates a new array by default. Even if dtype is the same before and after conversion, unnecessary copying can be avoided by requesting copy=False.
3. Indexing, Slicing and Boolean Mask
base index
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
a[0, 1] # 2
a[0] # first line
a[:, 1] # second column
a[1:, :2] # The last two rows and the first two columns
Boolean Indexing
One of the most commonly used operations in data analysis.
a = np.array([10, 20, 30, 40, 50])
mask = a > 25
a[mask] # [30, 40, 50]
a[(a > 20) & (a < 50)]
Multiple conditions require the use of &, |, ~, and pay attention to the parentheses.
Fancy Indexing
Extract specified elements from an array of integer indices:
a[[0, 2, 4]] # [10, 30, 50]
One key difference from plain Slicing is that advanced indexing usually returns Copy, while plain slicing returns View.
4. Vectorization: Vectorized calculation
NumPy can perform batch operations directly on arrays, eliminating the need to manually write the Python loop.
a = np.array([1, 2, 3, 4])
a + 10
a * 2
a ** 2
np.sqrt(a)
np.log(a)
np.exp(a)
For example to normalize the entire array:
x = np.array([10, 20, 30, 40], dtype=float)
x_standardized = (x - x.mean()) / x.std()
Its core advantage is to reduce the element-by-element execution overhead of the Python layer, and implement batch calculations through underlying compilation.
Universal Functions(ufunc)
Many numerical functions in NumPy belong to ufunc.
For example:
np.add(a, 2)
np.multiply(a, 3)
np.maximum(a, 2)
np.abs(a)
np.isfinite(a)
They support array element-wise calculations and Broadcasting.
Vectorization is generally faster, but is not guaranteed to be more memory efficient for all operations because multiple array operations may create large intermediate arrays.
5. Broadcasting: Broadcast mechanism
Broadcasting allows element-wise operations on arrays that are not identical to Shape.
a = np.array([
[1, 2, 3],
[4, 5, 6],
])
b = np.array([10, 20, 30])
a + b
Result:
[[11, 22, 33],
[14, 25, 36]]
NumPy compares Shape starting from the rightmost dimension:
- Both dimensions are the same size; or
- At least one dimension has size 1.
Only when the conditions are met can Broadcast be achieved.
For example:
(3, 4)
( 4)
------
(3, 4)
and:
(3, 1)
(1, 4)
------
(3, 4)
The broadcast direction can be controlled by adding dimensions:
a = np.array([1, 2, 3])
b = np.array([10, 20])
a[:, None] + b[None, :]
Output:
[[11, 21],
[12, 22],
[13, 23]]
Broadcasting usually does not require an actual copy of the expanded input, but the final result and intermediate expressions may still consume a lot of memory.
6. Shape, Reshape and Axis
Reshape
a = np.arange(12)
a.reshape(3, 4)
a.reshape(2, 2, 3)
a.reshape(-1, 2)
Among them, -1 means that the dimension is automatically derived.
Transpose / Swapaxes
a = np.arange(6).reshape(2, 3)
a.T
np.transpose(a)
np.swapaxes(a, 0, 1)
For higher-dimensional arrays, you can use np.moveaxis() or np.transpose() to specify the dimension order.
Expand / Squeeze
a = np.array([1, 2, 3])
a[:, None].shape # (3, 1)
np.expand_dims(a, axis=0) # (1, 3)
np.squeeze(np.array([[1, 2, 3]])).shape # (3,)
The meaning of Axis
Assumptions:
a = np.array([
[1, 2, 3],
[4, 5, 6],
])
For aggregate functions:
np.sum(a) # 21
np.sum(a, axis=0) # [5, 7, 9], aggregated along the row direction
np.sum(a, axis=1) # [6, 15], aggregated along the column direction
Memory method:
axis=0: Eliminate row dimensions, leaving results in each column.axis=1: Eliminate column dimensions, leaving results per row.
You can also use keepdims=True to retain the aggregated dimensions to facilitate subsequent Broadcasting.
7. Data statistics and aggregation
Functions frequently used in daily data analysis:
| Function | API |
|---|---|
| Sum | np.sum() |
| mean | np.mean() |
| median | np.median() |
| Max/Min | np.max() / np.min() |
| standard deviation | np.std() |
| variance | np.var() |
| Quantile | np.percentile() / np.quantile() |
| Cumulative sum | np.cumsum() |
| maximum index | np.argmax() |
| Unique values and counts | np.unique(..., return_counts=True) |
For example:
x = np.array([10, 20, 20, 30, 100])
np.mean(x) # 36.0
np.median(x) # 20.0
np.std(x)
np.percentile(x, 90)
values, counts = np.unique(x, return_counts=True)
std() and var() of NumPy use ddof=0 by default; if a common sample standard deviation estimate is required, use ddof=1.
Conditional statistics
x = np.array([10, 20, 30, 40, 50])
x[x > 20].mean()
np.count_nonzero(x > 20)
np.sum(x > 20)
True and False can be treated as 1 and 0 respectively when summing.
8. Missing values and outlier processing
NumPy Floating point data often uses np.nan to represent missing values.
x = np.array([10.0, 20.0, np.nan, 40.0])
np.isnan(x)
np.nanmean(x)
np.nanmedian(x)
np.nanstd(x)
Normal np.mean(x) will get nan, while np.nanmean(x) will ignore NaN.
NaN, Inf check
np.isnan(x)
np.isinf(x)
np.isfinite(x)
Replace outliers
np.nan_to_num(
x,
nan=0.0,
posinf=100.0,
neginf=-100.0,
)
Clip
Used to limit the range of values:
x = np.array([-10, 5, 20, 100])
np.clip(x, 0, 50)
# [0, 5, 20, 50]
np.nan does not apply to all data types. For tabular data with complex missing value semantics, Pandas is often more appropriate.
9. Conditional conversion and sorting
np.where()
Select different values based on conditions:
scores = np.array([45, 80, 65, 90])
labels = np.where(scores >= 60, "pass", "fail")
Multiple conditions can use np.select():
conditions = [
scores >= 90,
scores >= 60,
]
choices = ["A", "B"]
grades = np.select(conditions, choices, default="C")
sort
x = np.array([30, 10, 50, 20])
np.sort(x) # Sorted values
np.argsort(x) # sorted index
Sort another array by index:
names = np.array(["A", "B", "C", "D"])
scores = np.array([85, 90, 70, 95])
indices = np.argsort(scores)[::-1]
names[indices]
scores[indices]
Top-k
When complete sorting is not required, argpartition() can be used:
top3_indices = np.argpartition(scores, -3)[-3:]
Note that Top-k returned by argpartition() is not guaranteed to be sorted internally.
10. Merge and split arrays
Concatenate
Splice along existing dimensions:
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
np.concatenate([a, b], axis=0)
Stack
Create a new dimension:
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
np.stack([x, y], axis=0) # (2, 3)
np.stack([x, y], axis=1) # (3, 2)
Common abbreviations:
np.vstack([x, y])
np.hstack([x, y])
np.column_stack([x, y])
Split:
np.split(np.arange(12), 3)
During data preprocessing, concatenate() and stack() are very commonly used. The key is to distinguish between , connecting along the existing dimensions, and to create a new dimension.
11. Random number generation
It is recommended to use np.random.default_rng() to create a random number generator.
rng = np.random.default_rng(seed=42)
rng.random(5) # [0, 1) Uniform distribution
rng.integers(0, 10, size=5) # random integer
rng.normal(0, 1, size=1000) # normal distribution
rng.choice([1, 2, 3], size=5) # random sampling
Scramble the data:
indices = rng.permutation(100)
Fixing Seed makes pseudo-random processes easier to reproduce in the same environment, but does not guarantee exactly the same results across all NumPy versions or computing environments.
Random numbers are often used for:
- Sampling.
- Model initialization.
- Simulation experiment.
- Bootstrap。
- Data is scrambled.
12. Linear algebra
NumPy provides basic linear algebra operations through np.linalg.
Matrix multiplication
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
a @ b
np.matmul(a, b)
Note that * is element-wise multiplication, while @ is matrix multiplication.
Commonly used API
| Function | API |
|---|---|
| Matrix multiplication | @ / np.matmul() |
| vector dot product | np.dot() |
| norm | np.linalg.norm() |
| Solve a system of linear equations | np.linalg.solve() |
| eigenvalue/eigenvector | np.linalg.eig() / eigh() |
| singular value decomposition | np.linalg.svd() |
| least squares | np.linalg.lstsq() |
Example:
vector = np.array([3.0, 4.0])
np.linalg.norm(vector) # 5.0
Solve :
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
x = np.linalg.solve(A, b)
It is generally not recommended to solve a system of linear equations through np.linalg.inv(A) @ b, and it is more appropriate to use solve() directly.
13. View, Copy and memory layout
This is one of the easiest parts of NumPy to introduce hidden errors.
View
View shares the underlying data with the original array.
a = np.array([10, 20, 30, 40])
b = a[1:3]
b[0] = 999
print(a)
# [10, 999, 30, 40]
Copy
Copy has an independent copy of the data.
a = np.array([10, 20, 30, 40])
b = a[1:3].copy()
b[0] = 999
print(a)
# [10, 20, 30, 40]
| Operation | usual behavior |
|---|---|
| Basic Slicing | View |
| Boolean Indexing | Copy |
| Fancy Indexing | Copy |
reshape() | View if possible, otherwise Copy |
transpose() | Usually View |
flatten() | Copy |
ravel() | As much as possible View |
These rules come from the NumPy data buffer and Strides mechanisms.
Strides
strides indicates how many bytes the underlying memory address needs to move when moving an element along each dimension.
a = np.arange(12, dtype=np.int32).reshape(3, 4)
a.strides # Commonly (16, 4)
This means:
- Move one row: offset 16 Bytes.
- Move one column: offset 4 Bytes.
NumPy can create View by modifying Shape and Strides, without copying the underlying array data.
C-contiguous / F-contiguous
- C-order: The last dimension changes the fastest and is usually continuous by row.
- F-order: The first dimension changes the fastest and is usually continuous by column.
a.flags["C_CONTIGUOUS"]
a.flags["F_CONTIGUOUS"]
b = np.ascontiguousarray(a)
Some low-level numerical computing libraries require specific memory layouts, and non-contiguous arrays may trigger implicit copies.
14. The relationship between NumPy and Pandas
NumPy is more suitable for:
- Large numeric arrays.
- Matrix operations.
- Mathematical and statistical functions.
- Array shape transformation.
- The underlying calculation of machine learning algorithms.
Pandas is more suitable for:
- Tabular data with column names and indexes.
- Different columns use different data types.
- GroupBy、Merge、Join。
- time series.
- Missing data and business data cleaning.
Common conversions:
import pandas as pd
import numpy as np
df = pd.DataFrame({
"age": [20, 30, 40],
"salary": [5000, 7000, 9000],
})
X = df[["age", "salary"]].to_numpy()
It should be noted that to_numpy() does not guarantee zero copy; whether to copy or not depends on the column type and underlying storage of DataFrame.
In actual data analysis, Pandas usually handles the table structure, and NumPy is responsible for underlying numerical calculations. The two are often used together.
15. Performance and usage precautions
The main performance advantages of NumPy come from batch operations, compact data representation, and low-level compilation implementation.
But still pay attention to:
- Avoid large Python element-by-element loops.
- Control
dtypeto avoid unnecessaryfloat64memory overhead. - Note the large temporary array produced by Broadcasting.
- Distinguish between View and Copy.
- Avoid repeating
np.append()ornp.concatenate()in the loop, and collect the last merge or pre-allocation first. - Don't be fooled into thinking that all operations on NumPy are zero copies.
- For data exceeding the capacity of RAM, chunking, Polars, DuckDB, or other suitable schemes should be considered.
Summary
For data analysis and data processing, it is recommended to focus on:
| Knowledge points | importance |
|---|---|
ndarray、shape、dtype | core |
| Indexing、Slicing、Boolean Mask | core |
| Vectorization、Broadcasting | core |
axis、reshape、transpose | core |
mean、std、percentile、unique | high frequency |
where、sort、argsort | high frequency |
| NaN, Inf, outlier processing | high frequency |
concatenate、stack | high frequency |
| Random Generator | Commonly used |
np.linalg | on demand |
| View / Copy / Strides | Important low-level features |
| C-order / F-order | Understand |
NumPy The three most critical concepts are:
ndarrayis not just a replacement for Python List, it is a multidimensional array with Shape, dtype and memory layout.- Vectorization and Broadcasting enable a large number of numerical calculations to be performed efficiently under the hood.
- View/Copy and Strides determine whether array operations share memory, which is very important for correctness and performance.