AI / ML

NumPy Basics

Numerical computing

NumPy Basics

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 mathematical functions to operate on these arrays.

Install NumPy

pip install numpy

Import NumPy

import numpy as np

Create Arrays

# Create a 1D array
arr = np.array([1, 2, 3, 4, 5])
print(arr)  # [1 2 3 4 5]

# Create a 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d)

# Create array with zeros
zeros = np.zeros((3, 4))
print(zeros)

# Create array with ones
ones = np.ones((2, 3))
print(ones)

# Create array with range
range_arr = np.arange(0, 10, 2)
print(range_arr)  # [0 2 4 6 8]

Array Operations

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Addition
print(a + b)  # [5 7 9]

# Multiplication
print(a * 2)  # [2 4 6]

# Dot product
print(np.dot(a, b))  # 32

# Mean
print(np.mean(a))  # 2.0

# Max and Min
print(np.max(a))  # 3
print(np.min(a))  # 1

Array Shape and Reshape

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape)  # (2, 3)

# Reshape
reshaped = arr.reshape(3, 2)
print(reshaped)

Tip: NumPy arrays are much faster than Python lists for numerical operations, especially with large datasets.