-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal.py
More file actions
650 lines (505 loc) · 20.2 KB
/
final.py
File metadata and controls
650 lines (505 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# ============================================================
# STUDENT PERFORMANCE ANALYSIS SYSTEM (Filters + Visualization)
# ============================================================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# -------------------------------
# LOAD DATASET
# -------------------------------
df = pd.read_csv("student_performance_6000.csv")
df["Average"] = df.loc[:, "Math":"Computer"].mean(axis=1)
filtered_df = df.copy()
# Active filters memory
active_filters = {
"gender": None,
"age": None,
"id": None,
}
# ============================================================
# APPLY FILTERS TO DATASET
# ============================================================
def apply_all_filters():
global filtered_df
temp = df.copy()
if active_filters["gender"]:
temp = temp[temp["Gender"] == active_filters["gender"]]
if active_filters["age"]:
min_age, max_age = active_filters["age"]
temp = temp[(temp["Age"] >= min_age) & (temp["Age"] <= max_age)]
if active_filters["id"]:
start_id, end_id = active_filters["id"]
temp = temp[(temp["Student_ID"] >= start_id) & (temp["Student_ID"] <= end_id)]
filtered_df = temp
# ============================================================
# WELCOME SCREEN
# ============================================================
def show_welcome_screen():
print("----------------------------------------")
print(" WELCOME TO MY PROJECT ")
print("----------------------------------------")
print("Topic : Student Performance Analysis System")
print("Submitted To: Prof. Shubham Verma")
print("Submitted By: Jadwinder Singh")
print("Course : MSc IT 1st Semester")
print("Subject : Data Analysis (MS-71)")
print("----------------------------------------\n")
# ============================================================
# BASIC MENU FUNCTIONS
# ============================================================
def show_introduction():
print("\n===== INTRODUCTION =====")
print("This project analyzes student performance using Python, Pandas, and NumPy.")
print("You can filter data and view interactive visualizations.\n")
def show_dataset():
print("\n===== FILTERED DATASET =====")
print(filtered_df)
def show_average_marks():
print("\n===== AVERAGE MARKS =====")
print(filtered_df[["Name", "Average"]])
def show_top_and_bottom():
if filtered_df.empty:
print("\nNo data available!")
return
top = filtered_df.loc[filtered_df["Average"].idxmax()]
low = filtered_df.loc[filtered_df["Average"].idxmin()]
print("\n===== TOP PERFORMER =====")
print(f"{top['Name']} | Avg = {top['Average']:.2f}")
print("\n===== LOWEST PERFORMER =====")
print(f"{low['Name']} | Avg = {low['Average']:.2f}")
def show_subject_average():
if filtered_df.empty:
print("\nNo data available!")
return
print("\n===== SUBJECT-WISE AVERAGE =====")
print(filtered_df.loc[:, "Math":"Computer"].mean())
def show_class_summary():
if filtered_df.empty:
print("\nNo data available!")
return
print("\n===== CLASS SUMMARY =====")
print(f"Class Average: {filtered_df['Average'].mean():.2f}")
print(f"Highest Avg: {filtered_df['Average'].max():.2f}")
print(f"Lowest Avg: {filtered_df['Average'].min():.2f}")
def show_above_class_average():
if filtered_df.empty:
print("\nNo data!")
return
cavg = filtered_df["Average"].mean()
above = filtered_df[filtered_df["Average"] > cavg]
print("\n===== STUDENTS ABOVE CLASS AVERAGE =====")
print(above[["Name", "Average"]])
# ============================================================
# FILTER MENU (BEFORE VISUALIZATION)
# ============================================================
def visualization_filter_menu():
global active_filters
while True:
print("\n===== VISUALIZATION FILTER OPTIONS =====")
print("1. No Filter (Show All)")
print("2. Filter by Gender")
print("3. Filter by Age Range")
print("4. Filter by Student ID Range")
print("5. Apply Multiple Filters")
print("6. Reset All Filters")
print("7. Start Visualization")
choice = input("Enter choice: ")
if choice == "1":
active_filters = {"gender": None, "age": None, "id": None}
apply_all_filters()
print("✔ Showing ALL students.")
elif choice == "2":
g = input("Enter Gender (Male/Female/Other): ").title()
active_filters["gender"] = g
apply_all_filters()
print(f"✔ Filter Applied: Gender = {g}")
elif choice == "3":
try:
a = int(input("Enter Min Age: "))
b = int(input("Enter Max Age: "))
active_filters["age"] = (a, b)
apply_all_filters()
print(f"✔ Age Filter Applied: {a}-{b}")
except:
print("❌ Invalid Age Input")
elif choice == "4":
try:
s = int(input("Enter Start ID: "))
e = int(input("Enter End ID: "))
active_filters["id"] = (s, e)
apply_all_filters()
print(f"✔ ID Filter: {s}-{e}")
except:
print("❌ Invalid ID Input")
elif choice == "5":
print("Enter values (press Enter to skip):")
g = input("Gender: ").title()
if g: active_filters["gender"] = g
try:
a = input("Min Age: "); b = input("Max Age: ")
if a and b:
active_filters["age"] = (int(a), int(b))
except: pass
try:
s = input("Start ID: "); e = input("End ID: ")
if s and e:
active_filters["id"] = (int(s), int(e))
except: pass
apply_all_filters()
print("✔ Multiple Filters Applied")
elif choice == "6":
active_filters = {"gender": None, "age": None, "id": None}
apply_all_filters()
print("✔ Filters Reset")
elif choice == "7":
print("\nStarting Visualization...")
apply_all_filters()
break
else:
print("❌ Invalid option")
# ============================================================
# VISUALIZATION WITH n / p / q
# ============================================================
def show_visualization():
if filtered_df.empty:
print("\nNo filtered records to visualize!")
return
total_graphs = 4
graph_index = 0
plt.close("all")
fig, ax = plt.subplots(figsize=(9, 5))
# -------------------------------
# DRAW GRAPH
# -------------------------------
def plot_graph(i):
ax.clear()
if i == 0:
ax.bar(filtered_df["Name"], filtered_df["Average"], color="skyblue")
ax.set_title("Average Marks")
ax.tick_params(axis="x", rotation=90, labelsize=6)
elif i == 1:
filtered_df.loc[:, "Math":"Computer"].mean().plot(kind="bar", ax=ax)
ax.set_title("Subject-wise Average")
elif i == 2:
ax.hist(filtered_df["Attendance(%)"], bins=10, edgecolor="black")
ax.set_title("Attendance Distribution (Histogram)")
ax.set_xlabel("Attendance %")
ax.set_ylabel("Number of Students")
elif i == 3:
ax.violinplot([filtered_df["Math"], filtered_df["Science"], filtered_df["English"],
filtered_df["History"], filtered_df["Computer"]],
showmeans=True)
ax.set_xticks([1,2,3,4,5])
ax.set_xticklabels(["Math","Science","English","History","Computer"])
ax.set_title("Subject-wise Marks Distribution (Violin Plot)")
fig.canvas.draw_idle()
# -------------------------------
# KEYBOARD CONTROLS
# -------------------------------
def on_key(event):
nonlocal graph_index
if event.key == "n": # Next
graph_index = (graph_index + 1) % total_graphs
plot_graph(graph_index)
elif event.key == "p": # Previous
graph_index = (graph_index - 1) % total_graphs
plot_graph(graph_index)
elif event.key == "q": # Quit
plt.close("all")
fig.canvas.mpl_connect("key_press_event", on_key)
plot_graph(graph_index)
plt.show()
# ============================================================
# MAIN MENU
# ============================================================
show_welcome_screen()
while True:
print("\n==============================")
print(" STUDENT PERFORMANCE ANALYSIS ")
print("==============================")
print("1. Introduction")
print("2. Show Dataset")
print("3. Show Average Marks")
print("4. Top & Bottom Performer")
print("5. Subject-wise Average")
print("6. Class Summary")
print("7. Students Above Class Average")
print("8. Save Output CSV")
print("9. Visualize Data with ")
print("10. Exit")
print("==============================")
ch = input("Enter your choice: ")
if ch == "1": show_introduction()
elif ch == "2": show_dataset()
elif ch == "3": show_average_marks()
elif ch == "4": show_top_and_bottom()
elif ch == "5": show_subject_average()
elif ch == "6": show_class_summary()
elif ch == "7": show_above_class_average()
elif ch == "8":
filtered_df.to_csv("filtered_output.csv", index=False)
print("✔ Saved as filtered_output.csv")
elif ch == "9":
visualization_filter_menu()
show_visualization()
elif ch == "10":
print("Exiting... Thank you!")
break
else:
print("❌ Invalid Choice")
# ============================================================
# STUDENT PERFORMANCE ANALYSIS SYSTEM (Filters + Visualization)
# ============================================================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# -------------------------------
# LOAD DATASET
# -------------------------------
df = pd.read_csv("student_performance_6000.csv")
df["Average"] = df.loc[:, "Math":"Computer"].mean(axis=1)
filtered_df = df.copy()
# Active filters memory
active_filters = {
"gender": None,
"age": None,
"id": None,
}
# ============================================================
# APPLY FILTERS TO DATASET
# ============================================================
def apply_all_filters():
global filtered_df
temp = df.copy()
if active_filters["gender"]:
temp = temp[temp["Gender"] == active_filters["gender"]]
if active_filters["age"]:
min_age, max_age = active_filters["age"]
temp = temp[(temp["Age"] >= min_age) & (temp["Age"] <= max_age)]
if active_filters["id"]:
start_id, end_id = active_filters["id"]
temp = temp[(temp["Student_ID"] >= start_id) & (temp["Student_ID"] <= end_id)]
filtered_df = temp
# ============================================================
# WELCOME SCREEN
# ============================================================
def show_welcome_screen():
print("----------------------------------------")
print(" WELCOME TO MY PROJECT ")
print("----------------------------------------")
print("Topic : Student Performance Analysis System")
print("Submitted To: Prof. Shubham Verma")
print("Submitted By: Jadwinder Singh")
print("Course : MSc IT 1st Semester")
print("Subject : Data Analysis (MS-71)")
print("----------------------------------------\n")
# ============================================================
# BASIC MENU FUNCTIONS
# ============================================================
def show_introduction():
print("\n===== INTRODUCTION ABOUT THE PROJECT =====\n")
print("The 'Student Performance Analysis System' is a Python-based project developed using the Pandas and NumPy libraries.")
print("It analyzes and evaluates the academic performance of students based on their marks and attendance records.\n")
print("The system performs data operations such as:")
print("- Calculating student-wise averages")
print("- Identifying top and bottom performers")
print("- Computing subject-wise averages")
print("- Displaying students who scored above the class average\n")
print("This project helps teachers and administrators gain insights into overall class performance and demonstrates how Python can be used effectively for data analysis.\n")
print("The system is completely offline, simple, and user-friendly.\n")
def show_dataset():
print("\n===== FILTERED DATASET =====")
print(filtered_df)
def show_average_marks():
print("\n===== AVERAGE MARKS =====")
print(filtered_df[["Name", "Average"]])
def show_top_and_bottom():
if filtered_df.empty:
print("\nNo data available!")
return
top = filtered_df.loc[filtered_df["Average"].idxmax()]
low = filtered_df.loc[filtered_df["Average"].idxmin()]
print("\n===== TOP PERFORMER =====")
print(f"{top['Name']} | Avg = {top['Average']:.2f}")
print("\n===== LOWEST PERFORMER =====")
print(f"{low['Name']} | Avg = {low['Average']:.2f}")
def show_subject_average():
if filtered_df.empty:
print("\nNo data available!")
return
print("\n===== SUBJECT-WISE AVERAGE =====")
print(filtered_df.loc[:, "Math":"Computer"].mean())
def show_class_summary():
if filtered_df.empty:
print("\nNo data available!")
return
print("\n===== CLASS SUMMARY =====")
print(f"Class Average: {filtered_df['Average'].mean():.2f}")
print(f"Highest Avg: {filtered_df['Average'].max():.2f}")
print(f"Lowest Avg: {filtered_df['Average'].min():.2f}")
def show_above_class_average():
if filtered_df.empty:
print("\nNo data!")
return
cavg = filtered_df["Average"].mean()
above = filtered_df[filtered_df["Average"] > cavg]
print("\n===== STUDENTS ABOVE CLASS AVERAGE =====")
print(above[["Name", "Average"]])
# ============================================================
# FILTER MENU (BEFORE VISUALIZATION)
# ============================================================
def visualization_filter_menu():
global active_filters
while True:
print("\n===== VISUALIZATION FILTER OPTIONS =====")
print("1. No Filter (Show All)")
print("2. Filter by Gender")
print("3. Filter by Age Range")
print("4. Filter by Student ID Range")
print("5. Apply Multiple Filters")
print("6. Reset All Filters")
print("7. Start Visualization")
choice = input("Enter choice: ")
if choice == "1":
active_filters = {"gender": None, "age": None, "id": None}
apply_all_filters()
print("✔ Showing ALL students.")
elif choice == "2":
g = input("Enter Gender (Male/Female/Other): ").title()
active_filters["gender"] = g
apply_all_filters()
print(f"✔ Filter Applied: Gender = {g}")
elif choice == "3":
try:
a = int(input("Enter Min Age: "))
b = int(input("Enter Max Age: "))
active_filters["age"] = (a, b)
apply_all_filters()
print(f"✔ Age Filter Applied: {a}-{b}")
except:
print("❌ Invalid Age Input")
elif choice == "4":
try:
s = int(input("Enter Start ID: "))
e = int(input("Enter End ID: "))
active_filters["id"] = (s, e)
apply_all_filters()
print(f"✔ ID Filter: {s}-{e}")
except:
print("❌ Invalid ID Input")
elif choice == "5":
print("Enter values (press Enter to skip):")
g = input("Gender: ").title()
if g: active_filters["gender"] = g
try:
a = input("Min Age: "); b = input("Max Age: ")
if a and b:
active_filters["age"] = (int(a), int(b))
except: pass
try:
s = input("Start ID: "); e = input("End ID: ")
if s and e:
active_filters["id"] = (int(s), int(e))
except: pass
apply_all_filters()
print("✔ Multiple Filters Applied")
elif choice == "6":
active_filters = {"gender": None, "age": None, "id": None}
apply_all_filters()
print("✔ Filters Reset")
elif choice == "7":
print("\nStarting Visualization...")
apply_all_filters()
break
else:
print("❌ Invalid option")
# ============================================================
# VISUALIZATION WITH n / p / q
# ============================================================
def show_visualization():
if filtered_df.empty:
print("\nNo filtered records to visualize!")
return
total_graphs = 4
graph_index = 0
plt.close("all")
fig, ax = plt.subplots(figsize=(9, 5))
# -------------------------------
# DRAW GRAPH
# -------------------------------
def plot_graph(i):
ax.clear()
if i == 0:
ax.bar(filtered_df["Name"], filtered_df["Average"], color="skyblue")
ax.set_title("Average Marks")
ax.tick_params(axis="x", rotation=90, labelsize=6)
elif i == 1:
filtered_df.loc[:, "Math":"Computer"].mean().plot(kind="bar", ax=ax)
ax.set_title("Subject-wise Average")
elif i == 2:
ax.hist(filtered_df["Attendance(%)"], bins=10, edgecolor="black")
ax.set_title("Attendance Distribution (Histogram)")
ax.set_xlabel("Attendance %")
ax.set_ylabel("Number of Students")
elif i == 3:
ax.violinplot([filtered_df["Math"], filtered_df["Science"], filtered_df["English"],
filtered_df["History"], filtered_df["Computer"]],
showmeans=True)
ax.set_xticks([1,2,3,4,5])
ax.set_xticklabels(["Math","Science","English","History","Computer"])
ax.set_title("Subject-wise Marks Distribution (Violin Plot)")
fig.canvas.draw_idle()
# -------------------------------
# KEYBOARD CONTROLS
# -------------------------------
def on_key(event):
nonlocal graph_index
if event.key == "n": # Next
graph_index = (graph_index + 1) % total_graphs
plot_graph(graph_index)
elif event.key == "p": # Previous
graph_index = (graph_index - 1) % total_graphs
plot_graph(graph_index)
elif event.key == "q": # Quit
plt.close("all")
fig.canvas.mpl_connect("key_press_event", on_key)
plot_graph(graph_index)
plt.show()
# ============================================================
# MAIN MENU
# ============================================================
show_welcome_screen()
while True:
print("\n==============================")
print(" STUDENT PERFORMANCE ANALYSIS ")
print("==============================")
print("1. Introduction")
print("2. Show Dataset")
print("3. Show Average Marks")
print("4. Top & Bottom Performer")
print("5. Subject-wise Average")
print("6. Class Summary")
print("7. Students Above Class Average")
print("8. Save Output CSV")
print("9. Visualize Data with ")
print("10. Exit")
print("==============================")
ch = input("Enter your choice: ")
if ch == "1": show_introduction()
elif ch == "2": show_dataset()
elif ch == "3": show_average_marks()
elif ch == "4": show_top_and_bottom()
elif ch == "5": show_subject_average()
elif ch == "6": show_class_summary()
elif ch == "7": show_above_class_average()
elif ch == "8":
filtered_df.to_csv("filtered_output.csv", index=False)
print("✔ Saved as filtered_output.csv")
elif ch == "9":
visualization_filter_menu()
show_visualization()
elif ch == "10":
print("Exiting... Thank you!")
break
else:
print("❌ Invalid Choice")