NumPy is a powerful library in Python for numerical computing. It provides support for arrays, matrices, and many mathematical functions that operate on these data structures. NumPy is widely used in data science, machine learning, scientific computing, and many other fields due to its efficiency and ease of use.
You can install NumPy using pip:
pip install numpy
To use NumPy, you first need to import it:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) # Output: [1 2 3 4 5]
arr = np.zeros((2, 3))
print(arr) # Output: [[0. 0. 0.]
# [0. 0. 0.]]
arr = np.ones((2, 3))
print(arr) # Output: [[1. 1. 1.]
# [1. 1. 1.]]
arr = np.eye(3)
print(arr) # Output: [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
arr = np.arange(0, 10, 2)
print(arr) # Output: [0 2 4 6 8]
arr = np.linspace(0, 1, 5)
print(arr) # Output: [0. 0.25 0.5 0.75 1. ]
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # Output: (2, 3)
print(arr.ndim) # Output: 2
print(arr.size) # Output: 6
print(arr.dtype) # Output: dtype('int64')
NumPy allows element-wise operations and broadcasting:
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(arr1 + arr2) # Output: [5 7 9]
print(arr1 * arr2) # Output: [ 4 10 18]
print(arr1 + 5) # Output: [6 7 8]
NumPy arrays can be indexed and sliced similarly to Python lists:
arr = np.array([1, 2, 3, 4, 5])
print(arr[0]) # Output: 1
print(arr[1:4]) # Output: [2 3 4]
print(arr[:3]) # Output: [1 2 3]
print(arr[::2]) # Output: [1 3 5]
NumPy provides functions for aggregating data:
arr = np.array([1, 2, 3, 4, 5])
print(np.sum(arr)) # Output: 15
print(np.mean(arr)) # Output: 3.0
print(np.max(arr)) # Output: 5
print(np.min(arr)) # Output: 1
print(np.std(arr)) # Output: 1.4142135623730951
Broadcasting allows NumPy to perform operations on arrays of different shapes:
arr = np.array([1, 2, 3])
print(arr + 1) # Output: [2 3 4]
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix + arr) # Output: [[2 4 6]
# [5 7 9]]
NumPy includes a submodule for random number generation:
rand_array = np.random.rand(3, 3) # Uniform distribution
rand_ints = np.random.randint(0, 10, size=(3, 3)) # Random integers
rand_norm = np.random.randn(3, 3) # Standard normal distribution