NumPy Basics
What is NumPy?
NumPy (Numerical Python) is a fundamental library for scientific computing in Python. It provides powerful tools for working with arrays, mathematical operations, and numerical computations. NumPy is essential for data science, machine learning, and scientific research.
Key Features of NumPy
Multidimensional Arrays
NumPy introduces the ndarray
(n-dimensional array) object, which allows efficient storage and manipulation of large datasets.
import numpy as np
## Creating a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
## Creating a 2D array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
Mathematical Operations
NumPy provides extensive mathematical functions and operations:
Operation |
Description |
Example |
Element-wise Operations |
Perform calculations on entire arrays |
arr1 * 2 |
Linear Algebra |
Matrix operations and transformations |
np.dot(arr1, arr2) |
Statistical Functions |
Mean, median, standard deviation |
np.mean(arr1) |
graph TD
A[NumPy Arrays] --> B[Contiguous Memory]
A --> C[Vectorized Operations]
B --> D[Faster Computation]
C --> D
Array Creation Methods
NumPy offers multiple ways to create arrays:
- From Python lists
- Using built-in generation functions
- Random number generation
## Different array creation methods
zeros_array = np.zeros((3, 3)) ## Array filled with zeros
ones_array = np.ones((2, 4)) ## Array filled with ones
random_array = np.random.rand(3, 3) ## Random values between 0 and 1
Core NumPy Concepts
Broadcasting
NumPy can perform operations between arrays of different shapes automatically.
Indexing and Slicing
Powerful techniques for accessing and manipulating array elements:
arr = np.array([1, 2, 3, 4, 5])
subset = arr[1:4] ## Selects elements from index 1 to 3
Data Types
NumPy supports various numerical data types:
- int32, int64
- float32, float64
- complex numbers
- Boolean arrays
Why Use NumPy?
- Efficient memory usage
- Fast computational capabilities
- Extensive mathematical functions
- Foundation for data science libraries
By mastering NumPy, you'll unlock powerful numerical computing capabilities in Python. LabEx recommends practicing these concepts to become proficient in scientific computing.