Introduction
NumPy is the fundamental package for scientific computing in Python, providing efficient array operations.
Creating Arrays
import numpy as np
# From list
arr = np.array([1, 2, 3, 4, 5])
# Range of values
arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
arr = np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
# Zeros and ones
zeros = np.zeros(5)
ones = np.ones((3, 3))
# Random arrays
rand = np.random.rand(3, 4) # Uniform [0, 1)
randn = np.random.randn(3, 4) # Normal distribution
randint = np.random.randint(1, 10, (3, 4)) # Integers
Array Attributes
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # (2, 3)
print(arr.ndim) # 2
print(arr.size) # 6
print(arr.dtype) # int64
Basic Operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # [5, 7, 9]
print(a * 2) # [2, 4, 6]
print(a ** 2) # [1, 4, 9]
print(np.sum(a)) # 6
print(np.mean(a)) # 2.0
Practice Problems
- Create array of first 20 even numbers
- Reshape array to different dimensions
- Calculate row-wise and column-wise sums
- Find index of maximum value
- Create identity matrix and array of random values