NumPy (Numerical Python) is a fundamental library for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of high-level mathematical functions to operate on these arrays. At its core, NumPy introduces the `ndarray` object, which is a powerful N-dimensional array that can store homogeneous data (i.e., all elements must be of the same type).
Key features and importance of NumPy:
- ndarray: The primary object in NumPy, `ndarray`, is a fast and flexible container for large datasets in Python. Arrays allow for efficient storage and manipulation of numerical data.
- Performance: NumPy operations are implemented in C or Fortran, making them significantly faster than equivalent Python list operations, especially for large datasets. This speed is crucial for scientific and data-intensive applications.
- Memory Efficiency: NumPy arrays consume less memory than Python lists for storing numerical data.
- Vectorized Operations: NumPy enables "vectorized" operations, meaning operations can be applied to entire arrays at once without explicit Python loops. This not only boosts performance but also leads to more concise and readable code. These operations are often performed using Universal Functions (ufuncs).
- Broadcasting: A powerful mechanism that allows NumPy to work with arrays of different shapes when performing arithmetic operations, making code more efficient and often reducing memory usage.
- Foundation for Data Science: NumPy forms the bedrock of many other essential Python libraries for data science and machine learning, including SciPy (scientific computing), Pandas (data manipulation and analysis), Matplotlib (plotting), and scikit-learn (machine learning).
- Mathematical Functions: It provides a comprehensive suite of mathematical functions, including linear algebra routines, Fourier transforms, and random number capabilities.
In essence, NumPy is indispensable for anyone working with numerical data in Python, offering powerful tools for array creation, manipulation, and computation.
Example Code
import numpy as np
1. Array Creation
print("--- Array Creation ---")
arr1 = np.array([1, 2, 3, 4, 5])
print("1D Array (arr1):", arr1)
print("Type of arr1:", type(arr1))
print("Shape of arr1:", arr1.shape) (5,)
arr2 = np.array([[10, 20, 30], [40, 50, 60]])
print("\n2D Array (arr2):\n", arr2)
print("Shape of arr2:", arr2.shape) (2, 3)
Create an array of zeros
zeros_arr = np.zeros((3, 4))
print("\nArray of Zeros (3x4):\n", zeros_arr)
Create an array of ones
ones_arr = np.ones((2, 2))
print("\nArray of Ones (2x2):\n", ones_arr)
Create an array with a range of numbers
range_arr = np.arange(0, 10, 2) Start, Stop (exclusive), Step
print("\nArray from arange(0, 10, 2):", range_arr)
2. Basic Operations
print("\n--- Basic Operations ---")
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
Element-wise addition
c = a + b
print("Element-wise addition (a + b):", c)
Element-wise multiplication
d = a - b
print("Element-wise multiplication (a - b):", d)
Scalar multiplication
e = a - 2
print("Scalar multiplication (a - 2):", e)
Universal Function (ufunc) - square root
sqrt_a = np.sqrt(a)
print("Square root of a (np.sqrt(a)):", sqrt_a)
3. Indexing and Slicing
print("\n--- Indexing and Slicing ---")
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print("Original Matrix:\n", matrix)
Access a single element
print("Element at [0, 1]:", matrix[0, 1]) Output: 2
Slice rows and columns
print("First row:", matrix[0, :]) Output: [1 2 3]
print("Last column:", matrix[:, -1]) Output: [3 6 9]
print("Sub-matrix (rows 0-1, cols 0-1):\n", matrix[0:2, 0:2]) Output: [[1 2] [4 5]]
4. Reshaping
print("\n--- Reshaping ---")
flat_arr = np.arange(1, 10)
print("Flat array:", flat_arr) [1 2 3 4 5 6 7 8 9]
reshaped_arr = flat_arr.reshape(3, 3)
print("Reshaped to 3x3:\n", reshaped_arr)








numpy