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.

⏱ 25 min• Beginner• Jupyter / Colab

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.

Ek number: Python list me 1 crore integers add karne me ~2 second. NumPy array me wahi kaam ~10 millisecond — 200x fast. Reason: Python list = pointer array (har element object, type check har baar), NumPy = packed C data (ek loop, zero type checks).

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
Interview trap: "NumPy slice copy hai ya view?" — VIEW. Isliye 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

Interview question: "List aur ndarray me fundamental difference?" — List homogeneous nahi (mixed objects), dynamic size (pointer-based), slow math. ndarray homogeneous (fixed dtype), fixed memory block, vectorized C math, broadcasting support.
Lesson complete?

Lesson ho gaya? Ab next pe chalte hain — Pandas DataFrames.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course