NumPy Basics

Essential NumPy operations for arrays, mathematical operations, and data manipulation.

Import & Arrays

import numpy as np

# Create arrays
arr = np.array([1, 2, 3, 4, 5])
zeros = np.zeros((3, 4))  # 3x4 array of zeros
ones = np.ones((2, 3, 4))  # 2x3x4 array of ones
range_arr = np.arange(0, 10, 2)  # [0,2,4,6,8]
linspace = np.linspace(0, 1, 5)  # 5 evenly spaced values from 0 to 1

Array Operations

# Basic operations
arr + 10  # add to all elements
arr * 2  # multiply all
arr1 + arr2  # element-wise addition
arr1 * arr2  # element-wise multiplication

# Aggregations
arr.sum()  # sum of all elements
arr.mean()  # average
arr.std()  # standard deviation
arr.min()  # minimum value
arr.max()  # maximum value

Indexing & Slicing

# Indexing
arr[0]  # first element
arr[-1]  # last element
arr[1:4]  # slice from index 1 to 3

# 2D arrays
arr2d = np.array([[1,2,3], [4,5,6]])
arr2d[0, 1]  # row 0, column 1 → 2
arr2d[:, 1]  # all rows, column 1 → [2, 5]
arr2d[0, :]  # row 0, all columns → [1, 2, 3]

Shape & Reshape

arr.shape  # get dimensions (rows, cols)
arr.reshape(2, 3)  # reshape to 2x3
arr.flatten()  # flatten to 1D array
arr.transpose()  # transpose matrix (swap rows/cols)
len(arr)  # length of first dimension