NumPy
NumPy (Numerical Python) is a powerful library used for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.
Key Features of NumPy:
- N-dimensional Arrays: NumPy introduces the
ndarray
(N-dimensional array) object, which is much more efficient than Python's built-in list for handling large datasets and numerical operations. - Vectorized Operations: You can perform element-wise operations on entire arrays without needing explicit loops, which makes computations faster.
- Broadcasting: NumPy allows operations on arrays of different shapes without explicitly reshaping them.
- Mathematical Functions: It provides a wide range of functions for linear algebra, statistical operations, random number generation, and more.
How to Install NumPy:
If you don't have NumPy installed, you can install it using pip
:
pip install numpy
Importing NumPy:
import numpy as np
1. Creating NumPy Arrays:
You can create NumPy arrays from Python lists or tuples.
Using np.array()
:
import numpy as np
# From a Python list
arr = np.array([1, 2, 3, 4])
print(arr)
Output:
[1 2 3 4]
Using np.zeros()
and np.ones()
:
You can create arrays filled with zeros or ones.
zeros_array = np.zeros(5) # Array of 5 zeros
ones_array = np.ones(3) # Array of 3 ones
print(zeros_array)
print(ones_array)
Output:
[0. 0. 0. 0. 0.]
[1. 1. 1.]
Using np.arange()
:
The np.arange()
function is similar to Python's range()
but returns a NumPy array.
arr = np.arange(0, 10, 2) # Start at 0, stop before 10, with a step of 2
print(arr)
Output:
[0 2 4 6 8]
Using np.linspace()
:
This function returns evenly spaced numbers over a specified range.
arr = np.linspace(0, 1, 5) # 5 evenly spaced numbers between 0 and 1
print(arr)
Output:
[0. 0.25 0.5 0.75 1. ]
2. Array Operations:
Element-wise Operations:
NumPy allows element-wise operations on arrays, meaning you can apply mathematical operations to entire arrays without using loops.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Addition
print(arr1 + arr2)
# Multiplication
print(arr1 * arr2)
# Exponentiation
print(arr1 ** 2)
Output:
[5 7 9]
[4 10 18]
[1 4 9]
Statistical Operations:
NumPy has a variety of statistical functions that can be applied to arrays.
arr = np.array([1, 2, 3, 4, 5])
# Sum of elements
print(np.sum(arr))
# Mean
print(np.mean(arr))
# Standard Deviation
print(np.std(arr))
# Maximum value
print(np.max(arr))
Output:
15
3.0
1.4142135623730951
5
3. Multi-dimensional Arrays:
NumPy supports multi-dimensional arrays (like matrices). You can easily create 2D or higher-dimensional arrays.
# Creating a 2D array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix)
# Accessing specific elements
print(matrix[0, 1]) # Element at first row, second column
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
2
Array Slicing:
Just like Python lists, you can slice NumPy arrays to get sub-arrays.
sub_matrix = matrix[:2, 1:] # Slicing to get the first two rows and last two columns
print(sub_matrix)
Output:
[[2 3]
[5 6]]
4. Matrix Operations:
NumPy provides functions for matrix operations, such as dot product, transpose, and more.
Dot Product:
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
# Dot product
print(np.dot(arr1, arr2))
Output:
11
Matrix Transpose:
matrix = np.array([[1, 2], [3, 4]])
# Transpose of the matrix
print(matrix.T)
Output:
[[1 3]
[2 4]]
5. Broadcasting:
Broadcasting allows NumPy to perform operations on arrays of different shapes without explicitly reshaping them.
Example: Adding a scalar to an array:
arr = np.array([1, 2, 3])
result = arr + 10 # Adds 10 to each element of the array
print(result)
Output:
[11 12 13]
6. Random Numbers:
NumPy provides a suite of functions for generating random numbers.
# Random float in the range [0, 1)
rand_float = np.random.rand(3, 2) # 3x2 array of random floats
print(rand_float)
# Random integers between 0 and 10
rand_int = np.random.randint(0, 10, size=(2, 3)) # 2x3 array of random integers
print(rand_int)
Output:
[[0.8054088 0.72223526]
[0.2342287 0.11179929]
[0.47867958 0.4511373 ]]
[[2 5 4]
[0 1 4]]
Summary:
- NumPy is essential for efficient numerical computations in Python.
- It provides N-dimensional arrays (ndarray), which are faster and more memory efficient than Python lists.
- Vectorized operations allow you to perform element-wise operations on entire arrays without explicit loops.
- NumPy offers a wide range of functions for mathematical, statistical, and random operations.