You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

考试管理程序添加记录后CSV有数据但程序显示空DataFrame

考试管理程序空DataFrame问题修复

问题描述

开发基于Python的考试管理项目,使用Pandas管理CSV记录。添加记录后数据已成功写入CSV文件,但在程序内选择查看或编辑操作时,终端显示空DataFrame。

核心原因

  1. 变量作用域错误:handle_main_choice函数中,修改后的data是局部变量,未同步回主函数维护的全局data对象,导致主程序始终使用初始加载的空DataFrame。
  2. 无效数据加载:选项6中调用load_data()但未将返回值赋值给任何变量,无法更新程序内的DataFrame。
  3. 其他数据修改操作(删除列、删除记录、更新记录等)均存在相同的局部变量问题,修改后的数据未传递回主程序。

修复方案

1. 调整函数返回逻辑,同步更新后的数据

将handle_main_choice和handle_graph_choice函数的返回值改为(data, continue_running)元组,让主程序能接收更新后的DataFrame。

2. 移除无效的load_data()调用

选项6中无需重新加载文件,直接使用内存中已更新的DataFrame即可。

3. 优化图形菜单逻辑

新增graph_menu函数处理图形菜单循环,确保图形操作后的数据也能同步回主程序。

修复后完整代码

import pandas as pd
import matplotlib.pyplot as plt
import os

FILE_PATH = "the path to the file/exam.csv"

def load_data():
    if os.path.exists(FILE_PATH):
        data = pd.read_csv(FILE_PATH)
        print("Data loaded successfully.")
        print(data.head())  
    else:
        print("File not found. Creating a new DataFrame.")
        columns = ["rollno", "name", "father_name", "adharrid", "age", "attempt", "lastattemptscore", "dateofbirth", "address", "phonenumber", "email"]
        data = pd.DataFrame(columns=columns)
    return data

def save_data(data):
    data.to_csv(FILE_PATH, index=False)
    print("Data saved successfully.")

def display_main_menu():
    print('*' * 80)
    print('                                  WELCOME TO EXAMINATION MANAGEMENT MENU    ')
    print('*' * 80)
    print('1. Show Examination Details\n')
    print('2. Show Data Columns \n')
    print('3. Display Top Records\n')
    print('4. Display Bottom Records\n')
    print('5. Display Specific Column\n')
    print('6. Add a New Record\n')
    print('7. Add a New Column\n')
    print('8. Delete a Column\n')
    print('9. Delete a Record\n')
    print('10. Update a Record\n')
    print('11. Move to Graph Menu\n')
    print('12. Exit\n')

def handle_main_choice(data, choice):
    if choice == 1:
        print(data)
    elif choice == 2:
        print(data.columns)
    elif choice == 3:
        n = int(input('Enter number of top records to display: '))
        print(data.head(n))
    elif choice == 4:
        n = int(input('Enter number of bottom records to display: '))
        print(data.tail(n))
    elif choice == 5:
        col_name = input('Enter column name to display: ')
        if col_name in data.columns:
            print(data[col_name])
        else:
            print(f'Column "{col_name}" does not exist.')
    elif choice == 6:
        new_record = {
            "rollno": input('Enter Roll Number: '),
            "name": input('Enter Name: '),
            "father_name": input('Enter Father Name: '),
            "adharrid": input('Enter Aadhar ID: '),
            "age": int(input('Enter Age: ')),
            "attempt": int(input('Enter Attempt Number: ')),
            "lastattemptscore": float(input('Enter Last Attempt Score: ')),
            "dateofbirth": input('Enter Date of Birth (YYYY-MM-DD): '),
            "address": input('Enter Address: '),
            "phonenumber": input('Enter Phone Number: '),
            "email": input('Enter Email: ')
        }
        new_df = pd.DataFrame([new_record])
        data = pd.concat([data, new_df], ignore_index=True)
        save_data(data)
    elif choice == 7:
        col_name = input('Enter new column name: ')
        default_value = input('Enter default value for the new column: ')
        if col_name not in data.columns:
            data[col_name] = default_value
            save_data(data)
        else:
            print(f'Column "{col_name}" already exists.')
    elif choice == 8:
        col_name = input('Enter column name to delete: ')
        if col_name in data.columns:
            data = data.drop(columns=[col_name])
            save_data(data)
        else:
            print(f'Column "{col_name}" does not exist.')
    elif choice == 9:
        index_no = int(input('Enter the index number of the record to delete: '))
        if index_no in data.index:
            data = data.drop(index_no)
            save_data(data)
        else:
            print(f'Index {index_no} does not exist.')
    elif choice == 10:
        index_no = int(input('Enter the index number of the record to update: '))
        if index_no in data.index:
            updated_record = {
                "rollno": input('Enter Roll Number: '),
                "name": input('Enter Name: '),
                "father_name": input('Enter Father Name: '),
                "adharrid": input('Enter Aadhar ID: '),
                "age": int(input('Enter Age: ')),
                "attempt": int(input('Enter Attempt Number: ')),
                "lastattemptscore": float(input('Enter Last Attempt Score: ')),
                "dateofbirth": input('Enter Date of Birth (YYYY-MM-DD): '),
                "address": input('Enter Address: '),
                "phonenumber": input('Enter Phone Number: '),
                "email": input('Enter Email: ')
            }
            data.loc[index_no] = updated_record
            save_data(data)
        else:
            print(f'Index {index_no} does not exist.')
    elif choice == 11:
        data = graph_menu(data)
    elif choice == 12:
        print("Exiting the system. Thank you!")
        return data, False
    return data, True

def display_graph_menu():
    print('*' * 80)
    print('                          GRAPH MENU                             ')
    print('*' * 80)
    print('1. Age Distribution Histogram\n')
    print('2. Attempt Distribution Bar Graph\n')
    print('3. Last Attempt Score Scatter Plot\n')
    print('4. Exit to Main Menu\n')

def handle_graph_choice(data, choice):
    if choice == 1:
        plt.hist(data['age'].dropna(), bins=10, edgecolor='black')
        plt.xlabel('Age')
        plt.ylabel('Frequency')
        plt.title('Age Distribution')
        plt.show()
    elif choice == 2:
        attempt_counts = data['attempt'].value_counts().sort_index()
        attempt_counts.plot(kind='bar')
        plt.xlabel('Attempt Number')
        plt.ylabel('Number of Records')
        plt.title('Attempt Distribution')
        plt.show()
    elif choice == 3:
        plt.scatter(data['attempt'], data['lastattemptscore'])
        plt.xlabel('Attempt Number')
        plt.ylabel('Last Attempt Score')
        plt.title('Last Attempt Score vs Attempt Number')
        plt.show()
    elif choice == 4:
        return data, False
    return data, True

def graph_menu(data):
    while True:
        display_graph_menu()
        try:
            choice = int(input('Enter your choice: '))
            data, continue_running = handle_graph_choice(data, choice)
            if not continue_running:
                break
        except ValueError:
            print("Invalid input. Please enter a number.")
    return data

def main():
    data = load_data()
    while True:
        display_main_menu()
        try:
            choice = int(input('Enter your choice: '))
            data, continue_running = handle_main_choice(data, choice)
            if not continue_running:
                break
        except ValueError:
            print("Invalid input. Please enter a number.")

if __name__ == "__main__":
    main()

关键修复点说明

  • 所有修改DataFrame的操作,通过函数返回值将更新后的数据同步回主程序的data变量。
  • 移除选项6中无效的load_data()调用,避免冗余操作。
  • 新增独立的graph_menu函数,确保图形菜单操作后的数据能正确同步。

内容的提问来源于stack exchange,提问作者QBBT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 21:58:08