Numpy is a powerful Python library for numerical computing, providing efficient array operations, linear algebra, and random number generation. Below are practical examples for common tasks.
Basic Array Creation
import numpy as np
# Create a 4x3 array of zeros
np.zeros([4, 3])
# Create a 3x4 array of ones
np.ones([3, 4])
# Create a 3x2 array of random numbers (uniform [0, 1))
np.random.random([3, 2])
Matrix Properties and Operations
x = np.array([3, 5])
x.shape # (2,)
y = np.array([[3, 5, 2], [2, 4, 2]])
y.shape # (2, 3)
# Transpose
y.transpose()
# Add a number to all elements
z = y + 3
# Element-wise multiplication
z * y
# Matrix multiplication
np.matmul(x, z)
Basic Math Functions
x = np.array([3, 5])
np.exp(x) # Exponential
np.sin(x) # Sine
np.cos(x) # Cosine
np.tanh(x) # Hyperbolic tangent
Max, Min, Mean, and Norm
x = np.array([-10, 3, 5, 9, 21, 8])
np.max(x) # Maximum value
np.min(x) # Minimum value
x.max() # Maximum value (method)
x.min() # Minimum value (method)
x.mean() # Mean value
# Euclidean norm (L2 norm)
np.linalg.norm(x)
Random Arrays and Numbers (Uniform Distribution)
np.random.random([2, 1]) # 2x1 array
np.random.random([5, 6]) # 5x6 array
np.random.random() # Single random number