functions
unknown
plain_text
6 months ago
6.8 kB
5
Indexable
import pandas as pd from datetime import datetime import ast # Globalne promenljive students = {} student_id_counter = 1 csv_file_path = 'students.csv' # Fiksna lista predmeta subjects = [ "Mathematics", "Physics", "Chemistry", "Biology", "History", "Geography", "Computer Science", "English Language", "Philosophy", "Sociology" ] def write_students_to_csv(students: dict) -> None: """Snimanje studenata u CSV datoteku.""" try: df = pd.DataFrame.from_dict(students, orient='index') df.to_csv(csv_file_path, index_label='Student ID') print(f"Student data successfully saved to {csv_file_path}.") except Exception as e: print(f"An error occurred while saving: {e}") def load_students() -> None: """Učitavanje studenata iz CSV datoteke.""" global student_id_counter try: df = pd.read_csv(csv_file_path) df.columns = df.columns.str.strip() for _, row in df.iterrows(): student_id = int(row.name) students[student_id] = { 'first_name': row['first_name'], 'last_name': row['last_name'], 'school_class': row['school_class'], 'address': row['address'], 'date_of_birth': row['date_of_birth'], 'contact': row['contact'], 'grades': {} } student_id_counter = max(student_id_counter, student_id + 1) except FileNotFoundError: print("The file does not exist.") except pd.errors.EmptyDataError: print("The file is empty.") except Exception as e: print(f"An error occurred while loading: {e}") def get_current_year(): return datetime.now().year def add_student(first_name: str, last_name: str, school_class: str, address: str, dob: str, contact: str) -> str: """Dodavanje novog studenta.""" global students global student_id_counter school_class = f"{school_class}/{get_current_year()}" student_id = student_id_counter students[student_id] = { 'first_name': first_name, 'last_name': last_name, 'school_class': school_class, 'address': address, 'date_of_birth': dob, 'contact': contact, 'grades': {} } write_students_to_csv(students) student_id_counter += 1 return f"Student {first_name} {last_name} has been enrolled in class {school_class}." def view_subjects(): """Prikazivanje liste predmeta.""" for subject in subjects: print(subject) def update_grades_for_student(student_id: int, subject: str, new_grade: float) -> str: """Ažuriranje ocene za određenog studenta.""" if subject not in subjects: raise ValueError(f"Subject '{subject}' is not in the fixed list of subjects.") if student_id in students: students[student_id]['grades'][subject] = new_grade write_students_to_csv(students) return f"Grade for subject '{subject}' has been successfully updated for student ID: {student_id}." else: raise ValueError("Student ID does not exist.") def load_student_data_for_dropdown(csv_file_path): # Read the CSV file into a DataFrame df = pd.read_csv(csv_file_path) # Parse grades from string format to dictionary for each row df['grades'] = df['grades'].apply(lambda x: ast.literal_eval(x)) # Create the list of student dictionaries students = [ { "id": row["Student ID"], "name": f"{row['first_name']} {row['last_name']}", "class": row["school_class"], "grades": row["grades"] } for _, row in df.iterrows() ] return students # Load data from CSV file def load_student_data(): # Read the CSV file into a DataFrame df = pd.read_csv(csv_file_path) # Parse the 'grades' column from string to dictionary df['grades'] = df['grades'].apply(ast.literal_eval) # Normalize grades into separate columns for each subject grades_df = df['grades'].apply(pd.Series) # Concatenate original dataframe with the expanded grades, and drop the original grades column df = pd.concat([df, grades_df], axis=1).drop(columns=['grades']) return df # Function to calculate average grades for each subject in the selected class def calculate_class_averages(df, school_class): # Filter the DataFrame for the selected class class_df = df[df['school_class'] == school_class] # Select only the columns with grade information by filtering for numeric types grade_columns = class_df.select_dtypes(include=['float64', 'int64']).columns grade_columns = [col for col in grade_columns if col not in ['Student ID']] # Exclude 'Student ID' subject_averages = class_df[grade_columns].mean() # Calculate the mean for each subject return subject_averages ####OVO### # Load CSV data using pandas data = pd.read_csv("students.csv") # Replace "student_data.csv" with your CSV file path # Convert grades from string to dictionary data['grades'] = data['grades'].apply(eval) # Extract list of unique classes from the data classes = data['school_class'].unique() def calculate_average_grades(selected_class): # Filter data by the selected class class_data = data[data['school_class'] == selected_class] # Initialize a dictionary to store sum of grades for each subject subject_totals = {} subject_counts = {} for grades in class_data['grades']: for subject, grade in grades.items(): if subject not in subject_totals: subject_totals[subject] = 0 subject_counts[subject] = 0 subject_totals[subject] += grade subject_counts[subject] += 1 # Calculate average grades average_grades = {subject: subject_totals[subject] / subject_counts[subject] for subject in subject_totals} return average_grades def calculate_average_grades(school_class): # Filter data for the selected school class class_data = data[data['school_class'] == school_class] # Initialize dictionary to accumulate subject grades subject_grades = {} for grades in class_data['grades']: for subject, grade in grades.items(): if subject not in subject_grades: subject_grades[subject] = [] subject_grades[subject].append(grade) # Calculate the average grade for each subject avg_grades = {subject: sum(grades) / len(grades) for subject, grades in subject_grades.items()} return avg_grades
Editor is loading...
Leave a Comment