🔢 Introduction to NumPy

NumPy (Numerical Python) is the fundamental package for scientific computing in Python. It provides:

NumPy is the foundation for nearly all Python data science libraries, including pandas, scikit-learn, TensorFlow, and PyTorch.

Why NumPy is Essential


🛠️ Getting Started with NumPy

Installation and Import

# Install NumPy if you haven't already
# !pip install numpy

# Import NumPy
import numpy as np

Creating NumPy Arrays

# Creating arrays from Python lists
arr1 = np.array([1, 2, 3, 4, 5])
print(f"1D array: {arr1}")

# 2D array (matrix)
arr2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(f"2D array:\\\\n{arr2}")

# Check array dimensions and shape
print(f"Dimension: {arr2.ndim}")
print(f"Shape: {arr2.shape}")
print(f"Size: {arr2.size}")  # Total number of elements
print(f"Data type: {arr2.dtype}")

# Creating arrays with specific data types
arr_float = np.array([1, 2, 3, 4], dtype=np.float64)
print(f"Float array: {arr_float}, dtype: {arr_float.dtype}")

# Creating arrays with specific initial values
zeros = np.zeros((3, 4))  # 3x4 array of zeros
print(f"Zeros array:\\\\n{zeros}")

ones = np.ones((2, 3, 4))  # 3D array of ones
print(f"Ones array shape: {ones.shape}")

empty = np.empty((2, 3))  # Uninitialized array (values are whatever is in memory)
print(f"Empty array:\\\\n{empty}")

# Identity matrix
identity = np.eye(3)
print(f"3x3 Identity matrix:\\\\n{identity}")

# Range-based arrays
range_arr = np.arange(0, 10, 2)  # Similar to range(0, 10, 2)
print(f"Range array: {range_arr}")

# Evenly spaced numbers in a range
linspace = np.linspace(0, 1, 5)  # 5 evenly spaced numbers between 0 and 1
print(f"Linspace array: {linspace}")

# Random arrays
random_arr = np.random.random((2, 3))  # Random values between 0 and 1
print(f"Random array:\\\\n{random_arr}")

random_ints = np.random.randint(0, 10, (3, 3))  # Random integers between 0 and 9
print(f"Random integers:\\\\n{random_ints}")

# Normal distribution
normal_dist = np.random.normal(0, 1, (2, 3))  # Mean=0, Std Dev=1
print(f"Normal distribution:\\\\n{normal_dist}")