PART 1: NUMPY – “Python का Calculator + Turbo Engine”
Python की normal list धीमी होती है। Numpy array 100x तेज़ है क्योंकि ये C language में बना है।
1.Numpy क्या है?
Numpy क्या है?
बड़े-बड़े numbers, Matrix, Scientific calculation के लिए। Data Science की नींव।
Install: pip install numpy
2.Numpy Array बनाना
import numpy as np
List से Array
arr = np.array([1, 2, 3, 4, 5])
print(arr) # [1 2 3 4 5]
print(type(arr)) #
2D Array – Matrix
matrix = np.array([[1,2,3], [4,5,6]])
print(matrix)
Ready-made arrays
zeros = np.zeros((3,4)) # 3×4 के सारे 0
ones = np.ones((2,3)) # 2×3 के सारे 1
range_arr = np.arange(0, 10, 2) # 0 से 9 तक, 2 का gap: [0 2 4 6 8]
linear = np.linspace(0, 1, 5) # 0 से 1 के बीच 5 बराबर हिस्से
3.Shape, Size और Data Type
arr = np.array([[1,2,3],[4,5,6]])
print(arr.shape) # (2, 3) -> 2 row, 3 column
print(arr.size) # 6 -> total elements
print(arr.ndim) # 2 -> 2D array
print(arr.dtype) # int64
4.Indexing और Slicing – बहुत Important
arr = np.array([10,20,30,40,50])
print(arr[0]) # 10 – पहला element
print(arr[-1]) # 50 – आखिरी element
print(arr[1:4]) # [20 30 40] – 1 से 3 index तक
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(matrix[1, 2]) # 6 – 1st row, 2nd column
print(matrix[:, 0]) # [1 4 7] – सारी rows, 0th column
5.Maths – बिना Loop के
यही Numpy की power है। Vectorization बोलते हैं।
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.sqrt(a)) # [1. 1.414 1.732]
print(np.mean(a)) # 2.0
print(np.sum(a)) # 6
6.Random और Statistics
np.random.rand(3) # 0 से 1 के बीच 3 random number
np.random.randint(1,10,5) # 1 से 9 के बीच 5 random number
np.random.normal(0,1,100) # Normal distribution वाले 100 numbers
Numpy का सार:जब भी numbers का ढेर हो, Matrix हो, Calculation हो → Numpy use करो।
PART 2: PANDAS – “Excel on Steroids”
अगर Numpy engine है तो Pandas पूरी कार है। Table जैसा data handle करने के लिए।
1.Pandas क्या है?
Pandas = Panel Data
2 मुख्य चीजें: Series = 1 Column, DataFrame = पूरा Table
Install: pip install pandas
2.Series और DataFrame
import pandas as pd
Series – 1D लेबल वाला array
marks = pd.Series([88, 92, 79], index=[‘Ravi’, ‘Sita’, ‘Aman’])
print(marks[‘Sita’]) # 92
DataFrame – 2D Table
data = {
‘Name’: [‘Ravi’, ‘Sita’, ‘Aman’],
‘Math’: [88, 92, 79],
‘Science’: [85, 95, 80]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Math Science
0 Ravi 88 85
1 Sita 92 95
2 Aman 79 80
3.File से Data पढ़ना – सबसे ज्यादा काम का
df = pd.read_csv(‘students.csv’) # CSV पढ़ो
df = pd.read_excel(‘students.xlsx’) # Excel पढ़ो
df.to_csv(‘new.csv’, index=False) # CSV में save करो
4.Data को देखना – EDA की शुरुआत
df.head() # पहले 5 row
df.tail(3) # आखिरी 3 row
df.info() # Column का type, कितने null हैं
df.describe() # mean, std, min, max
df.shape # (rows, columns)
df.columns # सारे column के नाम
5.Data Select करना – loc vs iloc
यही सबसे confuse करता है।
loc = नाम से select करो
iloc = Number/Index से select करो
df = pd.DataFrame({‘Name’:[‘A’,’B’,’C’], ‘Marks’:[90,80,70]}, index=[10,20,30])
df.loc[20] # index 20 वाली row
df.iloc[1] # 1 नंबर वाली row = index 20 वाली
df[‘Name’] # पूरा Name column
df[[‘Name’,’Marks’]] # 2 column
df.loc[10:20, ‘Name’] # index 10 से 20 तक, Name column
6.Filter और Condition
#80 से ज्यादा Marks वाले
topper = df[df[‘Marks’] > 80]
#Math > 85 और Science > 90
df[(df[‘Math’]>85) & (df[‘Science’]>90)]
#नया Column
df[‘Total’] = df[‘Math’] + df[‘Science’]
df[‘Grade’] = np.where(df[‘Total’]>170, ‘A’, ‘B’)
7.Missing Data Handle करना
Real data में NaN बहुत आते हैं।
df.isnull().sum() # हर column में कितने null
df.fillna(0) # null को 0 से भरो
df.fillna(df.mean()) # null को average से भरो
df.dropna() # null वाली row हटा दो
8.Groupby – “Pivot Table जैसा”
#Class के हिसाब से Average Marks
df.groupby(‘Class’)[‘Marks’].mean()
#Multiple aggregation
df.groupby(‘Gender’).agg({
‘Math’: ‘mean’,
‘Science’: [‘max’, ‘min’]
})
9.Sort और Unique
df.sort_values(‘Marks’, ascending=False) # Marks से sort
df[‘City’].unique() # City में कितने अलग-अलग नाम
df[‘City’].value_counts() # हर City में कितने student
PART 3: NUMPY + PANDAS साथ में – “Student Performance Analysis”
अब असली प्रोजेक्ट। मान लो हमारे पास ये CSV है:
Name,Math,Science,English
Ravi,88,85,90
Sita,92,95,88
Aman,79,80,75
Priya,95,92,94
Full Code Example:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#1. Data Load
df = pd.read_csv(‘students.csv’)
print(df.head())
#2. नया Column – Numpy use करके
df[‘Total’] = df[[‘Math’,’Science’,’English’]].sum(axis=1)
df[‘Average’] = df[[‘Math’,’Science’,’English’]].mean(axis=1)
#3. Numpy से Grade देना
df[‘Grade’] = np.where(df[‘Average’] >= 90, ‘A’,
np.where(df[‘Average’] >= 80, ‘B’, ‘C’))
#4. Top 2 Students
top2 = df.sort_values(‘Total’, ascending=False).head(2)
print(“Top 2:”, top2[‘Name’].values)
#5. Subject wise Average – Numpy
subject_avg = np.mean(df[[‘Math’,’Science’,’English’]], axis=0)
print(“Subject Average:”, subject_avg)
#6. Correlation Heatmap
corr = df[[‘Math’,’Science’,’English’]].corr()
print(corr) # Math और Science कितने related हैं
#7. Save final result
df.to_csv(‘result.csv’, index=False)
Numpy vs Pandas – कब क्या use करें?
| काम | Use करो |
| Matrix Calculation, Image Data | Numpy |
| Table Data, CSV, Excel | Pandas |
| Stats, Mean, Std | दोनों |
| Groupby, Filter | Pandas |
| Speed critical loop | Numpy |
Rule: पहले Pandas से data साफ करो → फिर Numpy से calculation तेज करो।
Summary Exam Tips
1.Numpy: Speed के लिए। Array, Vector Maths
2.Pandas: Data handle करने के लिए। DataFrame, CSV, Groupby
3.3 सबसे important function: read_csv(), groupby(), loc/iloc
4.2सबसे बड़ी गलती:
(I)df[‘col’] और df[[‘col’]] में फर्क भूल जाना
(lI)oc और iloc mix कर देना
5.Project में flow: Load → Clean → Analyze → Visualize → Save
Students Clustering with Hierarchical Clustering using Pandas + Numpy + Scipy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from sklearn.preprocessing import StandardScaler
#Step 1: Sample Data बनाते हैं –
data = {
‘Student_ID’: [1,2,3,4,5,6,7,8,9,10],
‘Name’: [‘Aman’,’Riya’,’Karan’,’Sneha’,’Rahul’,’Pooja’,’Vijay’,’Anita’,’Rohit’,’Neha’],
‘Math’: [88,92,75,95,60,85,70,90,65,93],
‘Science’: [85,95,70,92,55,80,68,88,60,91],
‘English’: [90,88,78,94,62,82,72,89,64,92],
‘History’: [82,90,72,96,58,84,69,87,61,90]
}
df = pd.DataFrame(data)
print(“Original Data:”)
print(df.head())
#Step 2: सिर्फ Marks वाले Column लो – Clustering के लिए
X = df[[‘Math’,’Science’,’English’,’History’]]
#Step 3: Data Normalize करना बहुत जरूरी है
#वरना जिस subject के marks ज्यादा होंगे वही dominate करेगा
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_scaled = pd.DataFrame(X_scaled, columns=X.columns, index=df[‘Name’])
print(“\nNormalized Data:”)
print(X_scaled.head())
#Step 4: Hierarchical Clustering
#’ward’ method सबसे अच्छा है। ये variance minimize करता है
linked = linkage(X_scaled, method=’ward’)
#Step 5: Dendrogram बनाओ
plt.figure(figsize=(10, 6))
dendrogram(linked,
labels=df[‘Name’].tolist(),
orientation=’top’,
distance_sort=’descending’,
show_leaf_counts=True)
plt.title(‘Student Performance – Hierarchical Clustering Dendrogram’)
plt.xlabel(‘Student Name’)
plt.ylabel(‘Euclidean Distance’)
plt.tight_layout()
plt.savefig(‘dendrogram.png’) # Flask में यही image दिखा देना
plt.show()
#Step 6: कितने Cluster चाहिए? मान लो 3 Cluster
num_clusters = 3
df[‘Cluster’] = fcluster(linked, num_clusters, criterion=’maxclust’)
print(“\nStudents with Cluster Labels:”)
print(df[[‘Name’,’Math’,’Science’,’English’,’History’,’Cluster’]])
Step 7: हर Cluster का Analysis
print(“\n— Cluster Summary —“)
cluster_summary = df.groupby(‘Cluster’)[[‘Math’,’Science’,’English’,’History’]].mean()
print(cluster_summary)
#Step 8: Cluster को नाम दो
def label_cluster(row):
avg = row[[‘Math’,’Science’,’English’,’History’]].mean()
if avg >= 85: return “Top Performers”
elif avg >= 70: return “Average Performers”
else: return “Needs Improvement”
cluster_summary[‘Label’] = cluster_summary.apply(label_cluster, axis=1)
print(“\nCluster Labels:”)
print(cluster_summary)
2.Output कैसा आएगा?
Dendrogram.png बनेगा जिसमें दिखेगा कौन Student किसके पास है।
Console Output:
Students with Cluster Labels:
Name Math Science English History Cluster
Aman 88 85 90 82 1
Riya 92 95 88 90 1
Karan 75 70 78 72 2
— Cluster Summary —
Math Science English History
Cluster
1 92.00 93.25 91.00 91.75 -> Top Performers
2 78.75 75.50 80.00 76.75 -> Average Performers
3 61.67 57.67 62.67 59.67 -> Needs Improvement
3.Code को समझते हैं – 3 Important Line
1.StandardScaler() : Normalization। बिना इसके Math 95 और History 58 सीधा compare नहीं होगा।
2.linkage(X_scaled, method=’ward’) : यही Hierarchical Clustering कर रहा है। सारे students को धीरे-धीरे जोड़ता है।
3.fcluster(linked, 3, criterion=’maxclust’) : Dendrogram को 3 हिस्सों में काट दो।
4.Flask में कैसे डालें?
from flask import Flask, render_template, request
import pandas as pd
#ऊपर वाला सारा code एक function में
@app.route(‘/upload’, methods=[‘POST’])
def upload():
file = request.files[‘file’]
df = pd.read_csv(file)
# ऊपर वाला clustering code चलाओ
# dendrogram.png save करो
return render_template(‘result.html’, table=df.to_html(), img=’dendrogram.png’)