import numpy as np★Universal alias — alwaysnp.pip install numpyInstall (orconda install numpy).np.__version__Check the installed NumPy version.np.show_config()Show the BLAS/LAPACK backend in use.
np.array([1,2,3])★Build an array from a list / tuple.np.zeros((3,4))★Array of zeros with the given shape.np.ones((2,3))Array of ones with the given shape.np.full((2,3), 7)Array filled with a constant value.np.eye(4)Identity matrix — 1s on the diagonal.np.arange(0, 10, 2)★Range with a fixed step size.np.linspace(0, 1, 5)★N evenly spaced values in an interval.np.empty((2,2))Uninitialized array — fast, values are junk.
arr.shape★Tuple of sizes along each axis.arr.ndim★Number of axes / dimensions.arr.sizeTotal element count (product of shape).arr.dtype★Data type of the elements.arr.itemsizeBytes used by a single element.arr.nbytesTotal bytes consumed by the array.arr.astype(np.float32)★Cast to a new dtype — returns a copy.arr.tolist()Convert back to a plain Python list.
arr[2]★Element at index 2 (0-indexed).arr[1, 3]★Row 1, column 3 of a 2D array.arr[1:4]★Slice — elements at indices 1, 2, 3.arr[:, 1]★All rows, column 1.arr[::-1]Reverse the array along an axis.arr[start:stop:step]Full slice syntax, on any axis.basic slices → viewsviewNo copy is made; the data is shared.
arr[arr > 5]★Elements matching a boolean condition.arr[(arr>2)&(arr<9)]Combine masks with& | ~(notand/or).np.where(cond, a, b)★Elementwise conditional — a vectorized if/else.arr[[0,2,4]]Fancy indexing — pick rows by index list.np.nonzero(arr)Indices of non-zero (or True) elements.boolean / fancy → copycopyAlways returns new, independent memory.
arr.reshape(3, 4)★New shape, same data & element count.arr.T★Transpose — swap rows and columns.arr.flatten()copyCollapse to 1D — always a new array.arr.ravel()viewCollapse to 1D, sharing memory if possible.arr[:, np.newaxis]Insert a new length-1 axis.np.expand_dims(arr, axis=0)Insert an axis at a chosen position.np.squeeze(arr)Remove all length-1 axes.
np.concatenate([a,b], axis=0)★Join arrays along an existing axis.np.vstack([a,b])★Stack row-wise (adds rows, axis 0).np.hstack([a,b])★Stack column-wise (adds columns, axis 1).np.stack([a,b], axis=0)Join along a brand-new axis.np.split(arr, 3)Split into 3 equal-size sub-arrays.np.hsplit(arr, 2)Split horizontally (orvsplitvertically).
np.append(arr, [7,8])copyAppend values to the end of an array.np.insert(arr, 1, 99)Insert values before a given index.np.delete(arr, 2, axis=0)Remove a row/column by index.np.unique(arr)★Sorted, unique values in the array.np.unique(arr, return_counts=True)Unique values + how often each appears.
arr.copy()★Independent deep copy — safe to mutate.arr.view()New array object, same underlying memory.b = arr[1:3]aliasA slice is a view — editingbeditsarr.b = arr[arr > 0]copyBoolean indexing isolatesbfromarr.np.shares_memory(a, b)Check if two arrays alias the same data.
a + b a - b a * b a / b★Elementwise ops — no explicit loops needed.a ** 2Elementwise power.np.sqrt(arr) np.exp(arr) np.log(arr)★Elementwise math — all are ufuncs.np.abs(arr) np.round(arr)Absolute value / rounding.np.floor(arr) np.ceil(arr)Round down / up to the nearest integer.a @ b★Matrix multiplication — not elementwise.
compare shapes right-to-left★Trailing dims must match, or one must be 1.(3,4) + (4,) → (3,4)A row vector broadcasts across every row.(3,1) + (1,4) → (3,4)Column & row vectors combine into a grid.(3,4) + (2,4) → errorValueErrorMismatched dims that aren't 1 don't align.arr - arr.mean(axis=0)★Common pattern: centering columns via broadcasting.
arr.sum() arr.sum(axis=0)★Total, or per-column/row totals.arr.mean() arr.std() arr.var()★Average, standard deviation, variance.arr.min() arr.max()★Smallest / largest value.arr.argmin() arr.argmax()Index of the smallest / largest value.np.median(arr)Middle value of the sorted data.np.corrcoef(a, b)Pearson correlation coefficient matrix.np.cumsum(arr)Running cumulative sum.
np.sort(arr)★Sorted copy (arr.sort()sorts in place).np.argsort(arr)★Indices that would sort the array.np.searchsorted(arr, x)Index to insert x, keeping order.np.partition(arr, k)The k smallest elements moved to the front.np.where(condition)★Indices where a condition is True.
np.dot(a, b) / a @ b★Dot / matrix product.np.linalg.inv(A)Matrix inverse.np.linalg.det(A)Determinant of a square matrix.np.linalg.solve(A, b)★Solve Ax = b directly — faster thaninv.np.linalg.eig(A)Eigenvalues and eigenvectors.np.linalg.norm(v)Vector / matrix norm (length/magnitude).
rng = np.random.default_rng(seed)★Modern, recommended entry point.rng.random((2,3))★Uniform floats in [0, 1).rng.integers(0, 10, size=5)★Random ints — low inclusive, high exclusive.rng.normal(0, 1, size=100)Draws from a normal (Gaussian) distribution.rng.shuffle(arr)Shuffle an array in place.rng.choice(arr, size=3)Random sample drawn from an array.
np.array_equal(a, b)★True if same shape & all elements equal.np.allclose(a, b)True if elements match within float tolerance.np.isnan(arr)use thisNaN check — never usearr == np.nan.np.any(arr) np.all(arr)★At least one / every element truthy.np.logical_and(a, b)Elementwise AND (same as&on bool arrays).
np.union1d(a, b)Sorted union of two arrays.np.intersect1d(a, b)★Sorted values common to both arrays.np.setdiff1d(a, b)Values inabut not inb.np.isin(a, b)Boolean mask — is each element of a in b?
np.save('f.npy', arr)★Save one array — binary .npy format.np.load('f.npy')★Load a .npy / .npz file back into memory.np.savez('f.npz', a=arr1, b=arr2)Save several named arrays together.np.savetxt('f.csv', arr, delimiter=',')Write a plain-text / CSV file.np.loadtxt('f.csv', delimiter=',')Read a simple, fully-regular text file.np.genfromtxt('f.csv', delimiter=',')★Read text files, gracefully handling gaps.
vectorize, don't loopPython for-loops over elements are slow — use ufuncs.arr += 1truncatesIn-place op on an int array silently truncates floats.np.append() in a loopslowReallocates every call — build a list, thennp.array()once.int + float → floatMixing dtypes upcasts the whole array.slices are cheap; masks aren'tPrefer views (slicing) over fancy/boolean copies in hot loops.
int8 / int16 / int32 / int64Signed integers, 8 to 64 bits.uint8 / uint16 / uint32 / uint64Unsigned integers (no negatives).float32 / float64★Single / double precision (default: float64).boolTrue / False, stored as 1 byte.complex64 / complex128Complex numbers (real + imaginary parts).objectFallback for arbitrary Python objects — slow.str_Fixed-width Unicode string type.
axis=0★Collapse rows — operate down each column.axis=1★Collapse columns — operate across each row.axis=None (default)Flatten first, then aggregate the whole array.axis=-1Always means "the last axis", for any ndim.