pandas 基础设置(pd.values) data_preprocessing(缺失值)

本文是在做毕业设计 预处理(缺失值)部分的实践 参考pandas官方文档df.values

#例子1
>>> df2 = pd.DataFrame([('parrot',   24.0, 'second'),
...                     ('lion',     80.5, 1),
...                     ('monkey', np.nan, None)],
...                   columns=('name', 'max_speed', 'rank'))
>>> df2.dtypes
name          object
max_speed    float64
rank          object
dtype: object
>>> df2.values
array([['parrot', 24.0, 'second'],
       ['lion', 80.5, 1],
       ['monkey', nan, None]], dtype=object)
# 例子2
>>> df = pd.DataFrame({'age':    [ 3,  29],
...                    'height': [94, 170],
...                    'weight': [31, 115]})
>>> df
   age  height  weight
0    3      94      31
1   29     170     115
>>> df.dtypes
age       int64
height    int64
weight    int64
dtype: object
>>> df.values
array([[  3,  94,  31],
       [ 29, 170, 115]], dtype=int64)
  • 以上是官方文档的例子 下面进行测试验证

1.求max_val (min)

max_min

>>> list(df2.max(axis=0))
['parrot', 80.11]
# 找到了row对应的最大值
>>> list(df2.min(axis=0))
['lion', 24.0]

2.mean_values

求max + min / 2 的时候报错了 不知道为什么
在这里插入图片描述


>>> mean_val = list((df2.max(axis=0) + df2.min(axis=0)) / 2)

3. nan_value

在这里插入图片描述
发现原来 value是将其值做为一个array 舍弃 col raw 的 label (isnull()判断全局数据是否为null)

next step
接下来命名一下 并加上list 取每一行的具体形式

>>> nan_values = df2.isnull().values
>>> list(nan_values)
[array([False, False, False]), array([False, False, False]), array([False,  True,  True])]
>>> list(nan_values[0])
[False, False, False]
>>> list(nan_values[1])
[False, False, False]
>>> list(nan_values[2])
[False, True, True]
>>>

4. row_num

在这里插入图片描述
df.values:显示的是二维矩阵 显示行数 len(list(df.values))

>>> list(df.values)
[array([ 3, 94, 31]), array([ 29, 170, 115])]
>>> len(list(df.values))
2
>>> df
   age  height  weight
0    3      94      31
1   29     170     115
>>> df.values
array([[  3,  94,  31],
       [ 29, 170, 115]])

5. col_num

在这里插入图片描述
get col num: len(list(df.values[n]))

>>> df.values
array([[  3,  94,  31],
       [ 29, 170, 115]])
>>> list(df.values[1])
[29, 170, 115]
>>> len(list(df.values[1]))
3

delete concrete value

在这里插入图片描述

>>> df
   age  height  weight
0    3      94      31
1   29     170     115
>>> label = ['age']
>>> df.drop(label,axis=1)
   height  weight
0      94      31
1     170     115
>>> df_lab = df[label]
>>> print(df_lab)
   age
0    3
1   29

add the col label

在这里插入图片描述
发现drop的时候只是copy了输出 原值不会改变 需要赋予新的变量

>>> df
   age  height  weight
0    3      94      31
1   29     170     115
>>> label = ['age','height']
>>> df.drop(label,axis=1)
   weight
0      31
1     115
>>> df
   age  height  weight
0    3      94      31
1   29     170     115
>>> df_temp = df.drop(label,axis=1)
>>> df_temp
   weight
0      31
1     115
>>> df_lab = df[label]
>>> df_lab
   age  height
0    3      94
1   29     170
>>> print(df_lab)
   age  height
0    3      94
1   29     170
>>> df[label]
   age  height
0    3      94
1   29     170
>>> # 以上是删除的值
  • 以下是添加对应的col label & value
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
  • DataFrame.insert(loc, column, value, allow_duplicates=False)
    在这里插入图片描述
>>> for index,lab in enumerate(label):
...   df_temp.insert(index,lab,df_lab[lab])
...
>>> df_temp
   age  height  weight
0    3      94      31
1   29     170     115
>>> df_lab[lab]
0     94
1    170
Name: height, dtype: int64
>>> df_lab
   age  height
0    3      94
1   29     170

>>> for index,lab in enumerate(label):
...   print(index , lab )
...
0 age
1 height

处理缺失值 需要以上的值

使用循环

    for rn in range(row_num):
        #data_values_r = list(data_values[rn])
        nan_values_r = list(nan_values[rn])
        for cn in range(col_num):#column number
            if nan_values_r[cn] == False:
                df_temp.values[rn][cn] = 2 * (df_temp.values[rn][cn] - mean_val[cn])/(max_val[cn] - min_val[cn])
            else:
                print ('Wrong')
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个示例代码,实现了设置填空按钮,可设置训练集测试集比例,按后完成指定划分的功能: ``` import pandas as pd import tkinter as tk from tkinter import filedialog from sklearn.preprocessing import StandardScaler, LabelEncoder from sklearn.model_selection import train_test_split # 定义全局变量 file_path = "" train_ratio = 0.8 # 导入数据集 def import_csv_data(): global file_path file_path = filedialog.askopenfilename() # 读取CSV文件并显示在Text控件上 data = pd.read_csv(file_path) # 获取前5行数据 top_5 = data.head() # 将前5行数据插入到Text控件 txt_data.insert(tk.END, top_5) # 处理缺失值 def handle_missing_values(): global file_path # 读取CSV文件 data = pd.read_csv(file_path) # 处理缺失值 data.fillna(0, inplace=True) # 显示前10行数据 text_output.insert(tk.END, "处理缺失值成功,前10行数据如下:\n") text_output.insert(tk.END, str(data.head(10))) # 标准化数值型数据 def normalize_numeric_data(): global file_path # 读取CSV文件 data = pd.read_csv(file_path) # 提取数值型数据 numeric_data = data.select_dtypes(include=['float64', 'int64']) # 标准化数据 scaler = StandardScaler() normalized_data = scaler.fit_transform(numeric_data) # 将处理后的数据写回原数据框 data.loc[:, numeric_data.columns] = normalized_data # 显示前10行数据 text_output.insert(tk.END, "标准化数值型数据成功,前10行数据如下:\n") text_output.insert(tk.END, str(data.head(10))) # 划分训练集和测试集 def split_train_test(): global file_path, train_ratio # 读取CSV文件 data = pd.read_csv(file_path) # 划分数据集 train, test = train_test_split(data, train_size=train_ratio) # 显示训练集和测试集大小 text_output.insert(tk.END, "训练集大小:{}\n".format(len(train))) text_output.insert(tk.END, "测试集大小:{}\n".format(len(test))) # 创建主窗口 root = tk.Tk() root.title("数据处理工具") root.geometry("800x600") # 创建菜单栏 menubar = tk.Menu(root) filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label="导入数据集", command=import_csv_data) filemenu.add_command(label="处理缺失值", command=handle_missing_values) filemenu.add_command(label="标准化数值型数据", command=normalize_numeric_data) filemenu.add_command(label="划分训练集和测试集", command=split_train_test) menubar.add_cascade(label="文件", menu=filemenu) root.config(menu=menubar) # 创建控件 txt_data = tk.Text(root, height=10, width=100) txt_data.pack() text_output = tk.Text(root, height=10, width=100) text_output.pack() train_ratio_label = tk.Label(root, text="训练集比例:") train_ratio_label.pack() train_ratio_entry = tk.Entry(root) train_ratio_entry.pack() split_button = tk.Button(root, text="划分训练集和测试集", command=split_train_test) split_button.pack() # 运行主循环 root.mainloop() ``` 在这个示例代码中,我们添加了一个文本框和一个按钮来设置训练集测试集比例,当用户点击“划分训练集和测试集”按钮时,程序会调用`split_train_test()`函数来进行数据划分,并在文本框中显示训练集和测试集的大小。注意,在这个示例中,我们使用了`train_test_split`函数来划分数据集。该函数可以随机划分数据集,并且可以指定训练集和测试集的比例。在这个示例中,我们使用了一个全局变量`train_ratio`来保存训练集比例,默认为0.8。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值