KEMBAR78
NumPy Concepts and Tricks For Python Programs | PDF | Matrix (Mathematics) | Algebra
0% found this document useful (0 votes)
12 views11 pages

NumPy Concepts and Tricks For Python Programs

NumPy Concepts and Tricks for Python Programs Detailed about NumPy

Uploaded by

rajven123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views11 pages

NumPy Concepts and Tricks For Python Programs

NumPy Concepts and Tricks for Python Programs Detailed about NumPy

Uploaded by

rajven123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

🔢

NumPy
🐍 NumPy – Introduction
NumPy (Numerical Python) ek open-source Python library hai jo arrays
(ndarray) ke saath kaam karne ke liye bani hai. Ye fast mathematical
computations ke liye use hoti hai, aur ye data science, machine learning, AI,
aur scientific research ki backbone hai.
Normal Python lists slow hote hain aur bade data ke liye inefficient. NumPy
arrays kaafi fast, memory-efficient, aur optimized hote hain (C language ke
upar bane hue).

⚡ Features of NumPy
1. N-dimensional array (ndarray)

Normal Python list ke badle, NumPy multi-dimensional arrays deta hai.

Example: 1D (vector), 2D (matrix), 3D (tensor).

2. Fast Computation

NumPy operations C ke optimized code par chalte hain → list ke


comparison me 50x faster.

3. Broadcasting

NumPy 1
Different size arrays ke beech bhi arithmetic operations ho jate hain.

Example: [1,2,3] + 10 → [11,12,13] .

4. Mathematical Functions

Built-in: sum, mean, std, sin, log, sqrt, exp etc.

5. Random Module

Random number generation for simulations & ML (e.g., np.random.rand ,


np.random.randint ).

6. Reshaping & Slicing

Arrays ko easily reshape, slice, and index kar sakte ho (2D/3D).

7. Memory Efficiency

NumPy arrays same-type data store karte hain, jisse memory ka use
kam hota hai.

8. Integration with Other Libraries

SciPy, Pandas, TensorFlow, Scikit-learn → sab NumPy arrays par hi


based hain.

🎯✔️ Why We Use NumPy?


Speed → Python lists ke comparison me operations kaafi fast.

✔️ Convenience → Mathematical formulas likhna easy hota hai.


✔️ Large Dataset Handling → Millions of rows easily handle kar leta hai.
✔️ Foundation of Data Science → ML/AI frameworks NumPy arrays par hi
depend karte hain.
✔️ Matrix & Linear Algebra → Machine learning algorithms (dot product,
eigenvalues, matrix inversion).

✅ Example
Without NumPy (Python list)

NumPy 2
list1 = [1,2,3,4]
list2 = [5,6,7,8]
result = [list1[i] + list2[i] for i in range(len(list1))]
print(result) # [6, 8, 10, 12]

With NumPy

import numpy as np
arr1 = np.array([1,2,3,4])
arr2 = np.array([5,6,7,8])
print(arr1 + arr2) # [6 8 10 12]

👉 Dekh, kitna simple aur fast!


📌 Summary:
NumPy = Numerical Python (arrays + fast math operations).

Features = Speed, broadcasting, memory efficiency, reshaping, random


numbers, integration.

Why use = For scientific computing, ML, AI, data science.

🐍 NumPy Install
🔹 1. Install & Import
pip install numpy

import numpy as np

🔹 2. NumPy Arrays
NumPy ka core hai ndarray (N-dimensional array).

NumPy 3
List vs Array: Python list slow hai, NumPy array fast & efficient.

arr = np.array([1, 2, 3, 4])


print(arr) # [1 2 3 4]
print(type(arr)) # <class 'numpy.ndarray'>

2D Array

arr2d = np.array([[1, 2, 3], [4, 5, 6]])


print(arr2d)

👉 Attributes:
print(arr.ndim) # dimension
print(arr.shape) # rows, cols
print(arr.size) # total elements
print(arr.dtype) # data type

🔹 3. Creating Arrays
np.zeros((2,3)) # 2x3 matrix of 0
np.ones((3,3)) # 3x3 matrix of 1
np.eye(3) # 3x3 identity matrix
np.full((2,2), 7) # 2x2 matrix filled with 7
np.arange(0,10,2) # [0, 2, 4, 6, 8]
np.linspace(0,1,5) # 5 values equally spaced between 0 & 1
np.random.rand(2,2) # random values (0–1)
np.random.randint(1,10,(2,3)) # 2x3 random integers 1-9

🔹 4. Array Indexing & Slicing


arr = np.array([10,20,30,40,50])
print(arr[0]) # 10
print(arr[-1]) # 50
print(arr[1:4]) # [20 30 40]

NumPy 4
2D Access

arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr2d[0,1]) # row 0, col 1 → 2
print(arr2d[:,1]) # all rows, col 1 → [2 5 8]
print(arr2d[1,:]) # row 1 → [4 5 6]

👉 Fancy Indexing
arr = np.array([10,20,30,40])
print(arr[[0,2]]) # [10 30]

👉 Boolean Indexing
arr = np.array([10,20,30,40,50])
print(arr[arr > 25]) # [30 40 50]

🔹 5. Array Operations
Arithmetic

a = np.array([1,2,3])
b = np.array([4,5,6])

print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
print(a ** 2) # [1 4 9]

👉 Broadcasting (auto adjustment of shapes)


a = np.array([1,2,3])
print(a + 10) # [11 12 13]

🔹 6. Mathematical Functions

NumPy 5
arr = np.array([1,2,3,4,5])

print(np.sum(arr)) # 15
print(np.mean(arr)) # 3.0
print(np.median(arr)) # 3.0
print(np.std(arr)) # standard deviation
print(np.min(arr)) #1
print(np.max(arr)) # 5
print(np.sin(arr)) # sine values

👉 Axis-wise operations
arr2d = np.array([[1,2,3],[4,5,6]])
print(np.sum(arr2d, axis=0)) # column sum → [5 7 9]
print(np.sum(arr2d, axis=1)) # row sum → [6 15]

🔹 7. Reshaping Arrays
arr = np.arange(1,9)
print(arr.reshape(2,4)) # reshape to 2x4
print(arr.reshape(4,2)) # reshape to 4x2

👉 Flatten array
arr2d = np.array([[1,2],[3,4]])
print(arr2d.flatten()) # [1 2 3 4]

🔹 8. Stacking Arrays
a = np.array([1,2,3])
b = np.array([4,5,6])

print(np.vstack((a,b))) # vertical stack


print(np.hstack((a,b))) # horizontal stack

NumPy 6
🔹 9. Copy vs View
arr = np.array([1,2,3])
copy_arr = arr.copy()
view_arr = arr.view()

arr[0] = 99
print(copy_arr) # unaffected [1 2 3]
print(view_arr) # affected [99 2 3]

🔹 10. Useful Methods


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

print(np.sort(arr)) # sort
print(np.unique(arr)) # unique values
print(np.where(arr>25)) # indices where condition true
print(np.argmax(arr)) # index of max value
print(np.argmin(arr)) # index of min value

⚡✅ Summary
NumPy is for fast numerical computing
✅ Arrays = ndarray
✅ Array creation ( )
zeros, ones, arange, random

✅ Indexing, slicing, fancy indexing, boolean indexing


✅ Arithmetic + broadcasting
✅ Math functions ( )
sum, mean, std, sin…

✅ Reshape, flatten, stacking


✅ Copy vs View (important for memory mgmt)
✅ Useful methods ( )
sort, unique, where, argmax

NumPy 7
🐍 NumPy Functions
1️⃣ Array Creation Functions
import numpy as np

np.array([1,2,3]) # From Python list


np.zeros((2,3)) # 2x3 array filled with 0
np.ones((3,3)) # 3x3 array filled with 1
np.full((2,2), 7) # 2x2 filled with 7
np.eye(3) # Identity matrix (3x3)

np.arange(0,10,2) # [0 2 4 6 8]
np.linspace(0,1,5) # [0. 0.25 0.5 0.75 1.]

2️⃣ Inspection Functions


arr = np.array([[1,2,3],[4,5,6]])
arr.shape # (2,3)
arr.ndim # 2 (dimensions)
arr.size # 6 (total elements)
arr.dtype # int32/float64 etc.
arr.itemsize # size in bytes

3️⃣ Mathematical Functions


a = np.array([1,2,3,4])

np.sum(a) # 10
np.mean(a) # 2.5
np.median(a) # 2.5
np.std(a) # 1.118...
np.var(a) # 1.25
np.min(a) #1
np.max(a) #4

NumPy 8
np.sqrt(a) # [1. 1.41 1.73 2.]
np.exp(a) # exponential
np.log(a) # natural log
np.sin(a) # sine values

4️⃣ Array Manipulation


arr = np.arange(1,7)

arr.reshape(2,3) # reshape into 2x3


arr.flatten() # convert to 1D
arr.T # transpose

np.concatenate(([1,2,3],[4,5])) # [1 2 3 4 5]
np.hstack(([1,2,3],[4,5,6]))
np.vstack(([1,2,3],[4,5,6]))

5️⃣ Indexing & Slicing


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

arr[0] # 10
arr[-1] # 50
arr[1:4] # [20 30 40]

matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
matrix[0,1] # 2
matrix[:,1] # column [2 5 8]
matrix[1,:] # row [4 5 6]

6️⃣ Random Module


np.random.rand(3) # random floats (0-1)
np.random.randn(2,2) # normal distribution

NumPy 9
np.random.randint(1,10,5) # random integers

np.random.seed(42) # reproducible random

7️⃣ Linear Algebra


A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])

np.dot(A,B) # matrix multiplication


np.matmul(A,B) # same as dot
np.linalg.det(A) # determinant
np.linalg.inv(A) # inverse
np.linalg.eig(A) # eigenvalues & vectors

8️⃣ Statistical Functions


a = np.array([1,2,3,4,5])

np.percentile(a, 50) # median = 3


np.cumsum(a) # [1 3 6 10 15]
np.cumprod(a) # [1 2 6 24 120]

9️⃣ Comparison & Boolean


arr = np.array([10,20,30,40])
arr > 20 # [False False True True]
np.where(arr>20) # indexes of True
np.any(arr>35) # True
np.all(arr>5) # True
np.unique([1,2,2,3]) # [1 2 3]

🔟 Copy & Sorting


NumPy 10
arr = np.array([3,1,4,1,5])

np.sort(arr) # [1 1 3 4 5]
arr.copy() # deep copy

⚡ Quick Memory Tip for Notes


Creation → array, arange, linspace, zeros, ones, full, eye

Math → sum, mean, std, min, max, sqrt, log, sin

Shape → reshape, flatten, T

Random → rand, randint, randn, seed

Linear Algebra → dot, det, inv, eig

Stats → median, percentile, cumsum, cumprod

Check → any, all, where, unique

Connect with https://ashishkumar.vercel.app/

NumPy 11

You might also like