2. Numpy Basics
NumPy is a powerful Python library used for numerical and scientific computing. It provides support for arrays, matrices, and functions to perform mathematical operations efficiently.
1. What is NumPy?
NumPy stands for Numerical Python and provides a high-performance multidimensional array object (ndarray
) and tools for working with arrays. It’s the foundation of scientific computing in Python.
2. Installing NumPy
You can install NumPy using pip:
pip install numpy
3. Creating Arrays
The most basic object in NumPy is the ndarray
. You can create arrays in multiple ways.
3.1 Using np.array()
You can create an array from a list or tuple using np.array()
.
import numpy as np
# Creating a 1D arrayarr1 = np.array([1, 2, 3, 4])
# Creating a 2D array (Matrix)arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr1)print(arr2)
3.2 Array Creation Functions
NumPy provides handy functions to create arrays without needing explicit lists or tuples.
np.zeros(shape)
: Creates an array filled with zeros.np.ones(shape)
: Creates an array filled with ones.np.arange(start, stop, step)
: Creates an array with values ranging fromstart
tostop
(not inclusive) at intervals ofstep
.np.linspace(start, stop, num)
: Creates an array withnum
equally spaced values betweenstart
andstop
.
Example:
# Creating an array of zeroszeros_array = np.zeros((3, 3))
# Creating an array of onesones_array = np.ones((2, 4))
# Creating an array with a range of valuesrange_array = np.arange(0, 10, 2)
# Creating an array with evenly spaced valueslinspace_array = np.linspace(0, 1, 5)
print(zeros_array)print(ones_array)print(range_array)print(linspace_array)
4. Array Attributes
Important attributes to know about ndarray
objects:
shape
: The dimensions of the array.dtype
: The data type of the array elements.size
: Total number of elements in the array.ndim
: The number of dimensions (axes) of the array.
Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", arr.shape)print("Data type:", arr.dtype)print("Number of elements:", arr.size)print("Number of dimensions:", arr.ndim)
5. Array Indexing and Slicing
Indexing and slicing in NumPy arrays work similarly to Python lists but extend to multiple dimensions.
5.1 Indexing
arr = np.array([1, 2, 3, 4, 5])
# Accessing single elementsprint(arr[0]) # First elementprint(arr[-1]) # Last element
# Accessing elements in a 2D arrayarr2d = np.array([[1, 2, 3], [4, 5, 6]])print(arr2d[0, 2]) # Element at row 0, column 2
5.2 Slicing
You can slice arrays to get subarrays.
arr = np.array([1, 2, 3, 4, 5])
# Slicing 1D arrayprint(arr[1:4]) # Elements from index 1 to 3
# Slicing 2D arrayarr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])print(arr2d[1:, 1:]) # Slicing rows and columns
6. Array Operations
6.1 Mathematical Operations
NumPy allows element-wise operations on arrays, including addition, subtraction, multiplication, and division.
arr1 = np.array([1, 2, 3])arr2 = np.array([4, 5, 6])
# Element-wise additionprint(arr1 + arr2)
# Element-wise multiplicationprint(arr1 * arr2)
6.2 Broadcasting
When performing operations on arrays with different shapes, NumPy applies broadcasting rules to make the shapes compatible.
arr = np.array([1, 2, 3])
# Broadcasting a scalarprint(arr + 5) # Adds 5 to each element
7. Array Reshaping
You can change the shape of an array using reshape()
.
arr = np.arange(6) # Array with values 0 to 5reshaped = arr.reshape((2, 3)) # Reshape to 2 rows and 3 columnsprint(reshaped)
8. Stacking and Splitting Arrays
8.1 Stacking
You can stack arrays vertically or horizontally using vstack()
and hstack()
.
arr1 = np.array([1, 2, 3])arr2 = np.array([4, 5, 6])
# Vertical stackingprint(np.vstack((arr1, arr2)))
# Horizontal stackingprint(np.hstack((arr1, arr2)))
8.2 Splitting
You can split arrays into smaller arrays using split()
.
arr = np.array([1, 2, 3, 4, 5, 6])
# Split into 3 arraysprint(np.split(arr, 3))
9. Universal Functions (ufuncs)
NumPy provides universal functions (ufuncs) that operate on arrays element-wise, such as np.sqrt()
, np.log()
, np.exp()
, np.sin()
, etc.
arr = np.array([1, 4, 9, 16])
# Square root of each elementprint(np.sqrt(arr))
# Natural logarithmprint(np.log(arr))
10. Linear Algebra with NumPy
NumPy provides functions to perform matrix operations, including dot products, transposition, and inversion.
A = np.array([[1, 2], [3, 4]])B = np.array([[5, 6], [7, 8]])
# Matrix multiplication (dot product)print(np.dot(A, B))
# Transpose of a matrixprint(A.T)
11. Random Numbers in NumPy
NumPy includes functions to generate random numbers, which are useful in simulations and probabilistic algorithms.
# Random numbers between 0 and 1rand_arr = np.random.rand(3, 3)
# Random integers between a given rangerand_ints = np.random.randint(0, 10, size=(2, 3))
print(rand_arr)print(rand_ints)
Important Things in NumPy:
- Array Creation:
np.array()
,zeros()
,ones()
,arange()
,linspace()
. - Array Indexing/Slicing: Retrieve and modify elements and subarrays.
- Element-wise Operations: Perform math operations between arrays.
- Reshaping: Change the dimensions of arrays using
reshape()
. - Broadcasting: Perform operations on arrays of different shapes.
- Stacking/Splitting: Combine and split arrays.
- Linear Algebra:
np.dot()
, transposition, and matrix inversion.
This tutorial covers the foundational concepts of NumPy. You can dive deeper into each topic by exploring additional methods and functions.