Lesson 1 — Beginner
NumPy Fundamentals — Arrays se Vectorization
Data science ka har framework — Pandas, scikit-learn, TensorFlow — andar se NumPy chalta hai. Is lesson me hum seekhenge ki array kya hota hai, list se kaise alag hai, aur broadcasting se loops kaise khatam hote hain.
NumPy hai kya aur kyun?
WHAT
NumPy = Numerical Python. Ek library jo homogeneous C-arrays (ndarray) provide karti hai — same type ke elements ka contiguous memory block. Ek hi datatype hone ki wajah se operations CPU cache ke friendly hote hain.
WHEN
Jab bhi numbers ka batch ho — dataset columns, matrices, image pixels, model weights. 10,000+ numbers pe list-comprehension slow hoti hai, NumPy microseconds me kar deta hai.
WHERE
Har jagah: Pandas DataFrame internally NumPy arrays hain, scikit-learn inputs arrays maangta hai, deep learning weights arrays hain. Interview me "list vs array" sabse poochha jaane wala sawaal hai.
Pehla array
import numpy as np
a = np.array([1, 2, 3, 4, 5]) # 1-D array
print(a) # [1 2 3 4 5]
print(type(a)) # <class 'numpy.ndarray'>
print(a.dtype) # int64 (ek hi type - list jaisa object nahi)
print(a.shape) # (5,) - 5 elements ki 1-D tuple
print(a.ndim) # 1
print(a.size) # 5
b = np.array([[1, 2, 3],
[4, 5, 6]]) # 2-D array (matrix)
print(b.shape) # (2, 3) - 2 rows, 3 columns
# dtype control karo memory bachane ke liye
small = np.array([1, 2, 3], dtype=np.int8) # 1 byte per element
print(small.dtype) # int8
shape vs size: shape = har dimension me kitne elements, size = total elements. Matrix me len(shape) hi aapka number of dimensions (ndim) hai.
Indexing aur slicing
arr = np.array([10, 20, 30, 40, 50, 60])
print(arr[0]) # 10 (0-based, same as list)
print(arr[-1]) # 60 (negative index)
print(arr[1:4]) # [20 30 40] start inclusive, end exclusive
print(arr[::2]) # [10 30 50] har doosra element
print(arr[::-1]) # [60 50 40 30 20 10] reverse
# IMPORTANT: slice = VIEW hai, copy nahi
view = arr[1:4]
view[0] = 999
print(arr) # [ 10 999 30 40 50 60] - original badla!
# copy chahiye to .copy() likho
safe = arr[1:4].copy()
# 2-D indexing
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m[0, 2]) # 3 (row 0, col 2)
print(m[:, 1]) # [2 6] - poora column 1
print(m[1, :]) # [4 5 6] - poora row 1
arr[2:5] = 0 likhne se original mutate hota hai. Matlab chahiye to .copy().Operations aur broadcasting
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
# Element-wise (list me + concatenate hota tha!)
print(a + b) # [11 22 33 44]
print(a * 2) # [2 4 6 8] scalar ke saath
print(a ** 2) # [1 4 9 16]
print(np.sqrt(a)) # [1. 1.414 1.732 2.]
print(a > 2) # [False False True True] - boolean array
# Scalar har element pe broadcast hota hai - loop ki zaroorat nahi
mean_centered = a - a.mean()
# Shape rules (broadcasting):
# 1. Dimensions right se align karo
# 2. Har dimension ya same size ho, ya 1 ho
# 3. 1 wale dimension ko doosre ke liye "stretch" kiya jata hai
m = np.array([[1, 2, 3],
[4, 5, 6]]) # shape (2, 3)
row = np.array([10, 20, 30]) # shape (3,)
print(m + row) # [[11 22 33] [14 25 36]] - row har row me add hui
Vectorization vs loop — speed test
import time
data = np.random.rand(1_000_000)
# Loop style (banna mat karo)
start = time.time()
total = 0.0
for x in data: # Python-level loop
total += x ** 2
print("loop:", round(time.time() - start, 3), "sec")
# Vectorized style
start = time.time()
total = np.sum(data ** 2) # C-level, ek shot
print("numpy:", round(time.time() - start, 4), "sec")
# Typical result: loop ~0.25 sec, numpy ~0.002 sec (100x+)
Ye hi "vectorization" ka matlab hai — loop likhne ke bajaye poora array ek expression me. Production data pipelines me yahi pattern har jagah dikhega.
Exercise
Question: NumPy jo shape rules ke according arrays ko automatically stretch/expand karti hai uska naam kya hai? (1 word)
Question: 12 elements ke 1-D array ko 3x4 matrix banane ka NumPy method kaunsa hai? (1 word)
Common mistakes
- List se direct math:
[1,2] * 2Python me repeat karta hai, NumPy me multiply — dono ka matlab alag hai. - Copy kiye bina modify: slice = view. Analysis pipeline me ye silent data-corruption bana deta hai.
- dtype miss: 1 crore int64 = 80MB, int32 = 40MB. Large arrays me dtype choose karo.
- Loop habit:
for i in range(len(a)): c[i] = a[i] + b[i]likhne se pehle socho —c = a + bkyu nahi?
Lesson ho gaya? Ab next pe chalte hain — Pandas DataFrames.