Lesson 27 � Intermediate

NUMPY: NUMERICAL
COMPUTING KI DUNIYA.

NumPy data science ki foundation hai � arrays, matrices, mathematical operations sab NumPy se hota hai. Pandas, Scikit-learn, TensorFlow � ye sab NumPy pe built hain. Agar aapko data science ya ML seekhna hai toh NumPy pehla step hai.

? 22 min✓ IntermediatePrerequisite: Virtual Environments

WHY: NumPy kyun zaroori hai?

Socho aapko 10 lakh numbers ka average nikalna hai. Python list se karo toh loop chalega � slow aur memory-heavy. NumPy ka array directly C level pe kaam karta hai � 100x fast. Data science mein har cheez NumPy arrays se start hoti hai � data load karna, clean karna, analyze karna, ML model train karna.

ARRAY

np.array() se fast numerical arrays banti hain � Python list se 100x fast.

OPERATIONS

Vectorized operations � loops ki zaroorat nahi, poora array ek saath process hota hai.

RESHAPE

Array ka shape change karna � row se column, 1D se 2D, flexible transformations.

STATISTICS

Mean, median, std dev � sab built-in functions se instant calculation hoti hai.

WHEN: kab use hota hai

NumPy tab use hota hai jab aapko numerical data handle karna ho � data analysis, image processing, scientific computing, machine learning. Jab bhi large datasets ke saath kaam karo, NumPy sabse pehla tool hota hai. Data scientists, ML engineers, researchers � sab NumPy daily use karte hain.

HOW: NumPy basics

NumPy install aur import

python
# Install NumPy (terminal mein)
# pip install numpy

# Import NumPy
import numpy as np

# Ab np se sab functions call kar sakte ho
print(np.__version__)

import numpy as np standard convention hai � np short name hai jo sab data scientists use karte hain. Isse code clean aur readable rehta hai.

Array banana (1D)

python
import numpy as np

# Python list se array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(arr.shape) # (5,)
print(arr.dtype) # int32

# Float array
float_arr = np.array([1.5, 2.3, 3.7])
print(float_arr.dtype) # float64

np.array() se Python list converted hoti hai NumPy array mein. shape batata hai kitne elements hain, dtype batata hai data ka type kya hai.

2D Array (Matrix)

python
# 2D array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
print(matrix.shape) # (2, 3)
print(matrix.ndim) # 2

# 3D array
cube = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(cube.shape) # (2, 2, 2)
print(cube.ndim) # 3

2D array mein rows aur columns hote hain � ye tables aur matrices ke liye perfect hai. ndim batata hai array kitne dimensions ka hai.

Vectorized Operations (No loops!)

python
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([10, 20, 30, 40, 50])

# Element-wise operations
print(arr1 + arr2) # [11 22 33 44 55]
print(arr1 * 2) # [2 4 6 8 10]
print(arr1 ** 2) # [1 4 9 16 25]

# Mathematical functions
print(np.sqrt(arr1)) # [1. 1.41 1.73 2. 2.24]
print(np.exp(arr1)) # [2.72 7.39 20.09 54.6 148.4]

Vectorized operations ka matlab hai � loop lagane ki zaroorat nahi. Poora array ek saath process hota hai. Ye Python list ke compared 100x fast hai.

Array creation shortcuts

python
# Zero array
zeros = np.zeros(5)
print(zeros) # [0. 0. 0. 0. 0.]

# Ones array
ones = np.ones((3, 4))
print(ones.shape) # (3, 4)

# Range array
arr = np.arange(0, 20, 2)
print(arr) # [0 2 4 6 8 10 12 14 16 18]

# Linspace (evenly spaced)
arr = np.linspace(0, 1, 5)
print(arr) # [0. 0.25 0.5 0.75 1. ]

# Random array
random_arr = np.random.rand(5)
print(random_arr) # Random values between 0 and 1

NumPy mein arrays banane ke bohot saare shortcuts hain � zeros, ones, arange, linspace, random. Har ek ka specific use case hai.

Reshape: shape change karna

python
arr = np.arange(12)
print(arr) # [0 1 2 3 4 5 6 7 8 9 10 11]

# 1D se 2D
reshaped = arr.reshape(3, 4)
print(reshaped)
# [[0 1 2 3]
# [4 5 6 7]
# [8 9 10 11]]

# 2D se 1D
flat = reshaped.flatten()
print(flat) # [0 1 2 3 4 5 6 7 8 9 10 11]

# Transpose (rows <-> columns)
print(reshaped.T)
# [[0 4 8]
# [1 5 9]
# [2 6 10]
# [3 7 11]]

reshape() se array ka shape change hota hai � elements same rehte hain, sirf arrangement badalta hai. flatten() se 2D ko 1D bana sakte ho, T se transpose hota hai.

Statistics with NumPy

python
arr = np.array([10, 20, 30, 40, 50])

# Basic statistics
print(np.mean(arr)) # 30.0
print(np.median(arr)) # 30.0
print(np.std(arr)) # 14.14
print(np.var(arr)) # 200.0

# Min, Max, Sum
print(np.min(arr)) # 10
print(np.max(arr)) # 50
print(np.sum(arr)) # 150

# Index of min/max
print(np.argmin(arr)) # 0
print(np.argmax(arr)) # 4

# 2D statistics (axis wise)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(np.mean(matrix, axis=0)) # [2.5 3.5 4.5] (column-wise)
print(np.mean(matrix, axis=1)) # [2. 5.] (row-wise)

NumPy mein statistics functions bohot powerful hain � mean, median, std dev sab instant calculation hoti hai. axis parameter se decide karte ho ki calculation row-wise ya column-wise honi hai.

Indexing aur Slicing

python
arr = np.array([10, 20, 30, 40, 50])

# Single element
print(arr[0]) # 10
print(arr[-1]) # 50

# Slicing
print(arr[1:4]) # [20 30 40]
print(arr[::2]) # [10 30 50]

# 2D indexing
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix[0, 1]) # 2 (row 0, col 1)
print(matrix[:, 0]) # [1 4] (all rows, col 0)
print(matrix[1, :]) # [4 5 6] (row 1, all cols)

# Boolean indexing
arr = np.array([10, 25, 30, 45, 50])
mask = arr > 25
print(arr[mask]) # [30 45 50]

NumPy indexing Python list jaisi hai lekin zyada powerful � 2D arrays mein specific rows ya columns select kar sakte ho. Boolean indexing se filtered data nikal sakte ho.

Try it: NumPy Array PlaygroundArrays banao, operations karo, statistics nikalo
Code ko apni values se update karke run karein

Quick check

NumPy array banao [10, 20, 30, 40, 50] aur uska mean calculate karo.

Pehle import numpy as np likho, phir np.array() se array banao, phir np.mean() se average nikalo.

NumPy vs Python List

python
# Python list - slow
python_list = [1, 2, 3, 4, 5]
# python_list * 2 = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] (repeat hota hai)

# NumPy array - fast
np_array = np.array([1, 2, 3, 4, 5])
# np_array * 2 = [2, 4, 6, 8, 10] (element-wise multiply)

# Memory comparison
import sys
list_size = sys.getsizeof([1,2,3,4,5])
array_size = np.array([1,2,3,4,5]).nbytes
print(f"List: {list_size} bytes, Array: {array_size} bytes")

# Speed comparison
import time
large_list = list(range(1000000))
large_array = np.arange(1000000)

start = time.time()
sum(large_list)
print(f"List sum: {time.time()-start:.4f}s")

start = time.time()
np.sum(large_array)
print(f"Array sum: {time.time()-start:.4f}s")

NumPy arrays Python list se memory-efficient aur fast hain. List mein har element ka separate object hota hai, NumPy mein continuous memory block hota hai jo C level pe process hota hai.

Useful NumPy functions

Common mistakes

NumPy clear?

Ab aap arrays, operations, reshape aur statistics samajh gaye ho � Pandas seekhne ke liye ready ho!