NumPy function index
Search common NumPy functions, attributes, and methods by name or task.
Use the search below to find a function by name or by what you want to do. Expand an entry for a concise explanation, example, and link to the official documentation. The search applies only to this chapter's NumPy index.
The examples assume import numpy as np; random examples also use rng = np.random.default_rng(42).
Sources: NumPy array creation, Indexing, Array manipulation, Mathematical functions, Random sampling, Input and output
42 results in 6 categories
Create and inspect
Build arrays and check their structure.
np.arraynp.array(object, dtype=None)Create an ndarray from a Python sequence.
Nested sequences create multiple dimensions. Use dtype when you need an explicit numeric type.
import numpy as np
values = np.array([2, 4, 6])
print(values.shape) # (3,)NumPy documentation np.zerosnp.zeros(shape)Create an array filled with zeros.
Pass a tuple for a multidimensional shape. The default dtype is floating point.
import numpy as np
features = np.zeros((2, 3))
print(features.shape) # (2, 3)NumPy documentation np.onesnp.ones(shape)Create an array filled with ones.
Useful for initializing a numeric array or creating a same-shaped constant array.
import numpy as np
weights = np.ones((2, 2))
print(weights)NumPy documentation np.eyenp.eye(n)Create a 2D identity matrix.
The main diagonal contains ones; all other entries are zero.
import numpy as np
identity = np.eye(3)
print(identity.shape) # (3, 3)NumPy documentation np.arangenp.arange(start, stop, step)Create values spaced by a fixed step.
The stop value is excluded. Prefer integer steps when possible; floating-point steps can produce surprising lengths.
import numpy as np
ids = np.arange(3, 8)
print(ids) # [3 4 5 6 7]NumPy documentation np.linspacenp.linspace(start, stop, num)Create a fixed number of evenly spaced values.
Unlike arange, num specifies how many values to return. The endpoint is included by default.
import numpy as np
points = np.linspace(0, 1, num=5)
print(points) # [0. 0.25 0.5 0.75 1. ]NumPy documentation arr.shapearr.shapeRead the length of each array axis.
This is an attribute, not a function call. A 2-by-3 array has shape (2, 3).
import numpy as np
arr = np.zeros((2, 3))
print(arr.shape) # (2, 3)NumPy documentation arr.ndimarr.ndimRead the number of array axes.
A one-dimensional vector has ndim 1; a table with rows and columns has ndim 2.
import numpy as np
arr = np.zeros((2, 3))
print(arr.ndim) # 2NumPy documentation arr.sizearr.sizeRead the total number of elements.
For a regular array, size is the product of its shape dimensions.
import numpy as np
arr = np.zeros((2, 3))
print(arr.size) # 6NumPy documentation arr.dtypearr.dtypeRead the type used to store array elements.
Numeric arrays commonly use integer or floating-point dtypes. A dtype applies to the whole array.
import numpy as np
arr = np.array([1, 2, 3], dtype=np.int64)
print(arr.dtype) # int64NumPy documentation Reshape and combine
Change array layout, convert values, and join arrays.
arr.reshapearr.reshape(shape)Change array dimensions without changing the element count.
The requested shape must contain the same number of elements. Use -1 for one dimension that NumPy can infer.
import numpy as np
grid = np.arange(6).reshape(2, 3)
print(grid.shape) # (2, 3)NumPy documentation arr.T / np.transposearr.T | np.transpose(arr)Reverse or reorder the axes of an array.
For a 2D array, transpose swaps rows and columns. T is a convenient attribute.
import numpy as np
grid = np.arange(6).reshape(2, 3)
print(grid.T.shape) # (3, 2)NumPy documentation np.ravelnp.ravel(arr)Flatten an array into one dimension.
Returns a view when possible and a copy otherwise.
import numpy as np
grid = np.array([[1, 2], [3, 4]])
print(np.ravel(grid)) # [1 2 3 4]NumPy documentation arr.flattenarr.flatten()Return a flattened copy of an array.
Unlike ravel, flatten always returns a copy.
import numpy as np
grid = np.array([[1, 2], [3, 4]])
flat = grid.flatten()NumPy documentation arr.astypearr.astype(dtype)Convert array values to a chosen dtype.
The converted array is returned; the original array is unchanged.
import numpy as np
counts = np.array([2, 3, 4])
rates = counts.astype(float) / 10NumPy documentation arr.tolistarr.tolist()Convert an array to nested Python lists.
Elements are converted to compatible Python scalar types. A zero-dimensional array becomes a scalar.
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr.tolist()) # [[1, 2], [3, 4]]NumPy documentation np.concatenatenp.concatenate((a, b), axis=0)Join arrays along an existing axis.
All dimensions other than the joining axis must match.
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
print(np.concatenate((a, b))) # [1 2 3 4]NumPy documentation np.stacknp.stack((a, b), axis=0)Join arrays along a new axis.
Input arrays must have the same shape. Use concatenate to join along an existing axis.
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
print(np.stack((a, b)).shape) # (2, 2)NumPy documentation np.vstack / np.hstacknp.vstack((a, b)) | np.hstack((a, b))Stack arrays vertically or horizontally.
For 2D inputs, vstack joins rows and hstack joins columns.
import numpy as np
a = np.array([[1, 2]])
b = np.array([[3, 4]])
print(np.vstack((a, b)).shape) # (2, 2)NumPy documentation np.append / insert / deletenp.append(arr, values) | np.insert(...) | np.delete(...)Return arrays with values added, inserted, or removed.
These operations return new arrays rather than editing the original in place. Repeated edits can be inefficient because they copy data.
import numpy as np
values = np.array([1, 2, 3])
updated = np.append(values, 4)
print(updated) # [1 2 3 4]NumPy documentation Select and sort
Pick values by condition or index, then order or locate them.
Boolean maskarr[arr > value]Select elements that satisfy a condition.
Comparisons produce a Boolean array. Combine multiple conditions with parenthesized & or | expressions.
import numpy as np
values = np.array([10, 25, 40])
print(values[values > 20]) # [25 40]NumPy documentation Fancy indexingarr[row_indices, column_indices]Select arbitrary positions with integer arrays.
Paired row and column index arrays select coordinate pairs. Use np.ix_ to select every combination of rows and columns.
import numpy as np
grid = np.arange(12).reshape(3, 4)
print(grid[[0, 2], [1, 3]]) # [ 1 11]NumPy documentation np.sortnp.sort(arr, axis=-1)Return a sorted copy of an array.
Choose axis=0 to sort each column, axis=1 to sort each row, or axis=None to sort the flattened values.
import numpy as np
values = np.array([3, 1, 2])
print(np.sort(values)) # [1 2 3]NumPy documentation np.argsortnp.argsort(arr)Return the indices that would sort an array.
Use the returned indices to reorder a related array in the same way.
import numpy as np
values = np.array([30, 10, 20])
order = np.argsort(values)
print(order) # [1 2 0]NumPy documentation np.argmin / np.argmaxnp.argmin(arr) | np.argmax(arr)Return the index of a minimum or maximum value.
Without axis, the result is an index into the flattened array. Pass axis to get an index per slice.
import numpy as np
values = np.array([8, 3, 5])
print(np.argmin(values)) # 1NumPy documentation Math and statistics
Apply element-wise arithmetic and summarize values.
np.add / subtract / multiply / dividenp.add(a, b) | np.subtract(a, b) | ...Apply arithmetic element by element.
The equivalent operators are +, -, *, and /. For arrays, * is not matrix multiplication.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(np.multiply(a, b)) # [10 40 90]NumPy documentation np.mod / np.powernp.mod(a, b) | np.power(a, b)Calculate element-wise remainders or powers.
These correspond to the % and ** operators.
import numpy as np
values = np.array([2, 3, 4])
print(np.power(values, 2)) # [ 4 9 16]NumPy documentation np.reciprocal / square / sqrtnp.reciprocal(arr) | np.square(arr) | np.sqrt(arr)Compute reciprocals, squares, or square roots element-wise.
Use floating-point input for fractional reciprocals; integer input can produce integer results.
import numpy as np
values = np.array([1.0, 4.0, 9.0])
print(np.sqrt(values)) # [1. 2. 3.]NumPy documentation np.sin / np.cosnp.sin(arr) | np.cos(arr)Calculate sine or cosine for each value.
Angles are expressed in radians.
import numpy as np
angles = np.array([0, np.pi / 2])
print(np.sin(angles)) # [0. 1.]NumPy documentation np.min / max / sumnp.min(arr, axis=None) | ...Reduce values to a minimum, maximum, or total.
Use axis to reduce along rows or columns and keep one result per remaining dimension.
import numpy as np
table = np.array([[2, 5], [4, 1]])
print(np.sum(table, axis=0)) # [6 6]NumPy documentation np.cumsumnp.cumsum(arr, axis=None)Calculate cumulative sums in traversal order.
With an axis, compute a running total separately along each slice.
import numpy as np
values = np.array([2, 3, 5])
print(np.cumsum(values)) # [ 2 5 10]NumPy documentation np.mean / median / stdnp.mean(arr, axis=None) | ...Calculate common measures of center and spread.
Mean is sensitive to outliers; median is more robust. Standard deviation is reported in the input units.
import numpy as np
values = np.array([2.0, 4.0, 6.0])
print(np.mean(values)) # 4.0NumPy documentation np.isnan / np.nanmeannp.isnan(arr) | np.nanmean(arr, axis=None)Find NaN values or calculate a mean while ignoring them.
Ignoring missing values is a choice, not an automatic cleaning policy. nanmean cannot produce a meaningful result for an all-NaN slice.
import numpy as np
values = np.array([2.0, np.nan, 8.0])
print(np.nanmean(values)) # 5.0NumPy documentation Random data
Generate samples with a modern, reproducible random generator.
np.random.default_rngnp.random.default_rng(seed=None)Create a random Generator for sampling.
Pass a seed for repeatable examples and tests. Prefer Generator methods over legacy np.random.rand/randn/randint calls.
import numpy as np
rng = np.random.default_rng(42)
print(rng.integers(0, 10, size=4))NumPy documentation rng.randomrng.random(size)Draw uniform random values in the interval [0, 1).
Use size to choose the output shape.
import numpy as np
rng = np.random.default_rng(42)
samples = rng.random(size=(2, 3))NumPy documentation rng.standard_normalrng.standard_normal(size)Draw samples from a standard normal distribution.
The distribution has mean 0 and standard deviation 1; values are not limited to [-1, 1].
import numpy as np
rng = np.random.default_rng(42)
samples = rng.standard_normal(size=3)NumPy documentation rng.integersrng.integers(low, high, size)Draw random integers from low up to, but not including, high.
Use endpoint=True if the high value should be included.
import numpy as np
rng = np.random.default_rng(42)
print(rng.integers(1, 7, size=4))NumPy documentation rng.normalrng.normal(loc, scale, size)Draw samples from a normal distribution.
loc is the mean and scale is the standard deviation.
import numpy as np
rng = np.random.default_rng(42)
heights = rng.normal(loc=170, scale=8, size=5)NumPy documentation Files and linear algebra
Read and write numeric data, or solve a small linear system.
np.loadtxtnp.loadtxt(filename, delimiter=...)Read regularly formatted numeric text or CSV data.
Best suited to clean numeric files. Use skiprows or skip_header options when the file has a header.
import numpy as np
values = np.loadtxt("readings.csv", delimiter=",", skiprows=1)NumPy documentation np.genfromtxtnp.genfromtxt(filename, delimiter=...)Read numeric text data that may contain missing fields.
Can represent missing numeric fields with NaN or a chosen fill value. Mixed text and numeric tables may fit pandas better.
import numpy as np
values = np.genfromtxt(
"readings.csv", delimiter=",", skip_header=1, filling_values=np.nan
)NumPy documentation np.savetxtnp.savetxt(filename, arr, delimiter=...)Write an array to a readable text file.
Choose a delimiter and numeric format to control the exported text.
import numpy as np
np.savetxt("output.csv", values, delimiter=",", fmt="%.2f")NumPy documentation np.linalg.solvenp.linalg.solve(a, b)Solve the linear system a @ x = b.
The coefficient matrix must be square and full rank. Check the result by substituting it back into the equation.
import numpy as np
a = np.array([[2.0, 1.0], [1.0, 3.0]])
b = np.array([5.0, 6.0])
x = np.linalg.solve(a, b)NumPy documentation Finished the course? Visit the references and further reading.