Every array has attributes that describe its memory layout and data type.
# Shape (dimensions)print(f"Shape of A: {A.shape}")# Data typeprint(f"Data type of A: {A.dtype}")# Number of dimensionsprint(f"Number of dimensions: {A.ndim}")# Size (total number of elements)print(f"Total elements: {A.size}")
Shape of A: (2, 2)
Data type of A: float64
Number of dimensions: 2
Total elements: 4
Indexing and Slicing
Accessing elements in arrays is similar to Python lists but more powerful.
# 2D arrayM = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])# Access element at row 1, column 2 (0-indexed)print(f"Element at (1, 2): {M[1, 2]}")# Slicing: Get the first two rowsprint(f"First two rows:\n{M[:2, :]}")# Slicing: Get the last columnprint(f"Last column: {M[:, -1]}")
Element at (1, 2): 6
First two rows:
[[1 2 3]
[4 5 6]]
Last column: [3 6 9]
Element-wise Operations
NumPy supports element-wise operations, which are much faster than looping through lists.
a = np.array([1, 2, 3])b = np.array([4, 5, 6])# Additionprint(f"a + b = {a + b}")# Multiplication (element-wise)print(f"a * b = {a * b}")# Functionsprint(f"sin(a) = {np.sin(a)}")
a + b = [5 7 9]
a * b = [ 4 10 18]
sin(a) = [0.84147098 0.90929743 0.14112001]
Broadcasting
Broadcasting allows NumPy to work with arrays of different shapes when performing arithmetic operations.
A = np.array([[1, 2, 3], [4, 5, 6]])v = np.array([1, 0, 1])# Add vector v to each row of Aresult = A + vprint(f"Broadcasting result:\n{result}")
Broadcasting result:
[[2 2 4]
[5 5 7]]
Reshaping and Manipulation
Changing the shape of arrays is a common operation.
Reshaping
# Create a 1D array with 12 elementsa = np.arange(12)print(f"Original: {a}")# Reshape into 3x4 matrixB = a.reshape(3, 4)print(f"Reshaped (3x4):\n{B}")