决策树python实现代码1

目录

前言

数据:Titanic.csv,是一份泰坦尼克号的乘客信息及获救情况的统计,今天先完成数据清洗部分的代码逻辑。

代码实现

python 复制代码
# 导入第三方模块
import pandas as pd
from sklearn import model_selection
from sklearn.model_selection import GridSearchCV
from sklearn import tree

# 读入数据
Titanic = pd.read_csv(r'Titanic.csv')

# 删除无意义的变量,并检查剩余自字是否含有缺失值
Titanic.drop(['PassengerId','Name','Ticket','Cabin'], axis = 1, inplace = True)

# 对Sex分组,用各组乘客的平均年龄填充各组中的缺失年龄
fillna_Titanic = []
for i in Titanic.Sex.unique():
    update = Titanic.loc[Titanic.Sex == i,].fillna(value = {'Age': Titanic.Age[Titanic.Sex == i].mean()})
    fillna_Titanic.append(update)
Titanic = pd.concat(fillna_Titanic)

# 使用Embarked变量的众数填充缺失值
Titanic.fillna(value = {'Embarked':Titanic.Embarked.mode()[0]}, inplace=True)

# 将数值型的Pclass转换为类别型,否则无法对其哑变量处理
Titanic.Pclass = Titanic.Pclass.astype('category')
# 哑变量处理
dummy = pd.get_dummies(Titanic[['Sex','Embarked','Pclass']])
# 水平合并Titanic数据集和哑变量的数据集
Titanic = pd.concat([Titanic,dummy], axis = 1)
# 删除原始的Sex、Embarked和Pclass变量
Titanic.drop(['Sex','Embarked','Pclass'], inplace=True, axis = 1)
print(Titanic.head())

处理后的数据格式如下:

相关推荐
Python×CATIA工业智造1 天前
Python回调函数中携带额外状态的完整指南:从基础到高级实践
python·pycharm
害恶细君1 天前
【超详细】使用conda配置python的开发环境
开发语言·python·jupyter·pycharm·conda·ipython
java1234_小锋1 天前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 变量(Variable)的定义与操作
python·深度学习·tensorflow·tensorflow2
西望云天1 天前
The 2023 ICPC Asia Shenyang Regional Contest(2023沈阳区域赛CEJK)
数据结构·算法·icpc
我星期八休息1 天前
C++异常处理全面解析:从基础到应用
java·开发语言·c++·人工智能·python·架构
zh_xuan1 天前
LeeCode92. 反转链表II
数据结构·算法·链表·leecode
2401_841495641 天前
【数据结构】汉诺塔问题
java·数据结构·c++·python·算法·递归·
Q741_1471 天前
C++ 位运算 高频面试考点 力扣137. 只出现一次的数字 II 题解 每日一题
c++·算法·leetcode·面试·位运算
天特肿瘤电场研究所1 天前
专业的肿瘤电场疗法厂家
算法
哈里谢顿1 天前
Celery app 实例为何能在 beat、worker 等进程中“传递”?源码与机制详解
python