Home
Omar Hosney
NumPy Cheat Sheet 🐍📊
Array Creation
- np.array(): Create an array from a list.
np.array([1, 2, 3])
- np.zeros(): Create an array filled with zeros.
np.zeros((3, 3))
- np.ones(): Create an array filled with ones.
np.ones((2, 4))
- np.arange(): Create an array with a range of elements.
np.arange(0, 10, 2)
- np.linspace(): Create an array with evenly spaced numbers.
np.linspace(0, 1, 5)
Array Operations
- Arithmetic: Element-wise operations.
a + b, a - b, a * b, a / b
- Dot product: Matrix multiplication.
np.dot(a, b)
- Transpose: Flip array dimensions.
a.T
- Reshape: Change array shape.
a.reshape((3, 4))
- Flatten: Convert to 1D array.
a.flatten()
Array Indexing
- Slicing: Get a portion of an array.
a[1:4, 2:5]
- Boolean indexing: Select elements based on conditions.
a[a > 5]
- Fancy indexing: Select using integer arrays.
a[[1, 3, 4]]
Array Functions
- np.sum(): Sum of array elements.
np.sum(a)
- np.mean(): Average of array elements.
np.mean(a)
- np.max(), np.min(): Maximum and minimum values.
np.max(a), np.min(a)
- np.argmax(), np.argmin(): Indices of max and min values.
np.argmax(a), np.argmin(a)
Broadcasting
- Automatic: NumPy broadcasts arrays of different shapes.
a + np.array([1, 2, 3])
- Rules: Arrays must have compatible shapes for broadcasting.
# a: (3, 3), b: (3,) is valid
Linear Algebra
- np.linalg.inv(): Inverse of a matrix.
np.linalg.inv(a)
- np.linalg.det(): Determinant of a matrix.
np.linalg.det(a)
- np.linalg.eig(): Eigenvalues and eigenvectors.
np.linalg.eig(a)
- np.linalg.solve(): Solve linear equations.
np.linalg.solve(a, b)
Random Sampling
- np.random.rand(): Uniform distribution over [0, 1).
np.random.rand(3, 3)
- np.random.randn(): Standard normal distribution.
np.random.randn(3, 3)
- np.random.choice(): Random sample from given array.
np.random.choice([1, 2, 3], size=(2, 2))
Array Manipulation
- np.concatenate(): Join arrays along an axis.
np.concatenate((a, b), axis=0)
- np.split(): Split array into sub-arrays.
np.split(a, 3)
- np.stack(): Stack arrays along a new axis.
np.stack((a, b))
- np.tile(): Construct array by repeating.
np.tile(a, (2, 2))
File I/O
- np.save(): Save array to .npy file.
np.save('array.npy', a)
- np.load(): Load array from .npy file.
np.load('array.npy')
- np.savetxt(): Save array to text file.
np.savetxt('array.txt', a)
- np.loadtxt(): Load array from text file.
np.loadtxt('array.txt')