import tkinter as tk
import pandas as pd
import numpy as np
from tkinter import *
from tkinter import filedialog
from sklearn import preprocessing

data = pd.read_csv('crime.csv')
root = tk.Tk()
root.title('数据处理')
root.geometry('3000x2000')
yu = tk.Label(root, text='数据预处理', bg='red')
yu.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.1)

c = True
a1 = data.fillna(data.mean())
a = a1.fillna(method='bfill')

def jiance():
    t = data.isnull().any()
    global c
    global yu1
    if c == True:
        c = False
        yu1 = tk.Label(root, text=t)
        yu1.pack(side='bottom', expand=True)
    else:
        yu1.pack_forget()
        c = True

def tianchong():
    global a
    global yu2
    # a1=data.fillna(data.mean())
    # a=a1.fillna(method='bfill')  
    global c
    if c == True:
        c = False
        yu2 = tk.Label(root, text=a)
        yu2.pack(side='bottom', expand=True)
    else:
        yu2.pack_forget()
        c = True

def biaozhun():
    my_zscore = preprocessing.StandardScaler()
    # 检查 'LoanAmount' 列是否存在,如果不存在则进行处理
    if 'LoanAmount' in a.columns:
        a[['LoanAmount']] = my_zscore.fit_transform(a[['LoanAmount']])
    else:
        print('数据框中不存在名为 'LoanAmount' 的列。请检查数据或修改代码。')
    global c
    global yu3
    if c == True:
        c = False
        yu3 = tk.Label(root, text=a)
        yu3.pack(side='bottom', expand=True)
    else:
        yu3.pack_forget()
        c = True
        
def bianma():
    # 特征编码
    onehot = pd.get_dummies((a[['Gender']]), prefix='Gender')
    global c
    global yu4
    if c == True:
        c = False
        yu4 = tk.Label(root, text=onehot)
        yu4.pack(side='bottom', expand=True)
    else:
        yu4.pack_forget()
        c = True

btn3 = tk.Button(root, text='缺失值检测', command=lambda: jiance())
btn3.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.1)
btn4 = tk.Button(root, text='缺失值填充', command=lambda: tianchong())
btn4.place(relx=0.1, rely=0.5, relwidth=0.3, relheight=0.1)
btn5 = tk.Button(root, text='标准化', command=lambda: biaozhun())
btn5.place(relx=0.1, rely=0.6, relwidth=0.3, relheight=0.1)
btn6 = tk.Button(root, text='特征编码', command=lambda: bianma())
btn6.place(relx=0.1, rely=0.7, relwidth=0.3, relheight=0.1)
root.mainloop()

代码修改说明:

  1. biaozhun 函数中添加了检查 'LoanAmount' 列是否存在的部分:
    if 'LoanAmount' in a.columns:
        a[['LoanAmount']] = my_zscore.fit_transform(a[['LoanAmount']])
    else:
        print('数据框中不存在名为 'LoanAmount' 的列。请检查数据或修改代码。')
  1. 如果 'LoanAmount' 列不存在,则输出提示信息,并停止标准化操作。

解决问题:

通过添加列名检查,确保 biaozhun 函数在执行标准化操作之前,确认 'LoanAmount' 列存在于数据框 a 中,避免 KeyError 错误。

使用说明:

  1. 确保你的工作目录中存在一个名为 crime.csv 的 CSV 文件,并包含 LoanAmount 列。
  2. 运行代码,将会打开一个 GUI 窗口。
  3. 点击不同按钮,可以分别执行缺失值检测、填充、标准化和特征编码操作。
  4. 操作结果将显示在窗口底部。

注意:

代码示例仅供参考,实际使用中需要根据你的具体数据和需求进行调整。

相关资源:

Python数据预处理:缺失值处理、标准化和特征编码

原文地址: https://www.cveoy.top/t/topic/opVW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录