# 热力图和子图的绘制 # 读取数据 import pandas as pd data = pd.read_csv("data.csv") # 查看数据基本信息 print(data.info()) # 显示数据集前5行 print(data.head()) # 把Years in current job列和Home Ownership列转化为数字 # 先查看取值以及分布情况 print(data["Years in current job"].value_counts()) print(data["Home Ownership"].value_counts()) # 先进行映射,将字符串映射为数字 mapping = { "Years in current job": { "10+ years":10, "9 years":9, "8 years":8, "7 years":7, "6 years":6, "5 years":5, "4 years":4, "3 years":3, "2 years":2, "1 year":1, "< 1 year":0 }, "Home Ownership": { "Home Mortgage":0, "Rent":1, "Own Home":2, "Have Mortgage":3 }, } # 使用映射字典进行转换 data["Years in current job"] = data["Years in current job"].map(mapping["Years in current job"]) data["Home Ownership"] = data["Home Ownership"].map(mapping["Home Ownership"]) print(data.info()) print(data["Years in current job"].head()) # 检查映射后的结果 print(data["Home Ownership"].head()) # 检查映射后的结果 # 发现Years in current jobs有空值Nan,故采用中位数对其进行填补 Years_in_current_job_median= data["Years in current job"].median() data["Years in current job"] = data["Years in current job"].fillna(Years_in_current_job_median) # 检查是否还存在空值 print(data["Years in current job"].isnull().sum()) # 0 表明已经不存在空值Nan了 # 打印所有特征列 print(data.columns) # 手动找出所有连续变量 # 数据类型不能严格的作为区分连续变量与离散变量的依据 continuous_list = [ 'Annual Income', 'Years in current job', 'Tax Liens', 'Number of Open Accounts', 'Years of Credit History', 'Maximum Open Credit', 'Number of Credit Problems', 'Months since last delinquent', 'Bankruptcies', 'Current Loan Amount', 'Current Credit Balance', 'Monthly Debt', 'Credit Score' ] # 准备绘制热力图 import seaborn as sns import matplotlib.pyplot as plt import numpy as np import pandas as pd # 计算相关系数矩阵 correlation_matrix = data[continuous_list].corr() print(correlation_matrix) print(data[continuous_list]) # 返回的是由continuous_list列表中的列构成的dataFrame """ data[continuous_list]: data通常是一个pandas的DataFrame对象,它代表一个表格型的数据结构,类似于Excel表格。 continuous_list是一个包含列名的列表,代码通过data[continuous_list]从data数据框中 选取continuous_list里指定的列,返回一个只包含这些列的新DataFrame。 """ """ .corr(): 这是pandas中DataFrame对象的一个方法,用于计算数据框中各列之间的相关性系数。 默认情况下,它计算的是皮尔逊相关系数(Pearson correlation coefficient), 该系数衡量的是两个变量之间的线性相关程度,取值范围在-1到1之间, -1表示完全负相关,1表示完全正相关,0表示没有线性相关性。 corr()默认计算皮尔逊相关系数,你可以通过指定method参数来计算其他类型的相关性系数, 如method='spearman'计算斯皮尔曼相关系数。 """ # 设置图片清晰度 plt.rcParams['figure.dpi'] = 300 """ rcParams是matplotlib中的一个全局配置字典,它允许你在运行时修改matplotlib的各种默认设置。 'figure.dpi'是rcParams中的一个键,代表图表的分辨率,即每英寸点数(Dots Per Inch,简称DPI)。 """ # 绘制热力图 plt.figure(figsize = (12,10)) """ plt.figure()用于创建一个新的图形窗口,figsize参数以英寸为单位指定图形的宽度和高度, 这里设置宽度为12英寸,高度为10英寸。 """ sns.heatmap(correlation_matrix, annot = True, cmap = "coolwarm", vmin = -1, vmax = 1) """ sns.heatmap()用于绘制热力图。 correlation_matrix是之前计算得到的相关性矩阵,它是一个二维表格,存储着各特征间的相关性系数。 annot = True表示在热力图的每个单元格中显示具体的相关性数值。 cmap = "coolwarm"指定颜色映射,"coolwarm" 是一种颜色方案,冷色调(蓝色)代表负相关,暖色调(红色)代表正相关。 vmin = -1和vmax = 1 分别设置颜色映射的最小值和最大值,因为相关性系数的取值范围是-1到1,所以这样设置可确保完整显示相关性范围。 """ # 为图形添加标题,标题内容为 "Correlation Heatmap of Continuous Features" plt.title("Correlation Heatmap of Continuous Features") plt.show() """ 热力图本质上只能对连续值进行绘制,对于数值型的离散值其实是不合适用热力图的, 所以最好采用手动的方式对变量的类型进行划分 """import pandas as pd import matplotlib.pyplot as plt # 定义要绘制的特征 # 任选4个,重点是掌握子图的绘制方法 features = ["Annual Income", "Years in current job", "Tax Liens", "Number of Open Accounts"] # 设置图片清晰度 plt.rcParams['figure.dpi'] = 300 # 创建一个包含2行2列的子图布局 fig, axes = plt.subplots(2, 2, figsize = (12,10)) """ 主要功能是创建一个包含多个子图的图形窗口。具体来说,它会创建一个2行2列的子图网格, 也就是总共4个子图,同时设置整个图形窗口的大小为宽12英寸、高10英寸 fig:这是一个 Figure 对象,代表整个图形窗口。 你可以使用这个对象来设置图形的全局属性,比如保存图形、设置图形的标题等 axes:这是一个二维的Axes对象数组,每个 Axes 对象代表一个子图。 你可以通过索引来访问特定的子图,例如axes[0, 0]表示第一行第一列的子图, axes[1, 1]表示第二行第二列的子图。 """ # 手动指定特征索引进行绘图 i = 0 feature = features[i] axes[0, 0].boxplot(data[feature].dropna()) """ dropna()是pandas的Series或DataFrame对象的一个方法,其作用是移除数据中的缺失值(NaN)。 在绘制箱线图之前移除缺失值,是为了保证绘图数据的有效性。 """ axes[0, 0].set_title(f"Boxplot of {feature}") # 设置图片的标题 axes[0, 0].set_ylabel(feature) # 设置y轴的标签 i = 1 feature = features[i] axes[0, 1].boxplot(data[feature].dropna()) axes[0, 1].set_title(f"Boxplot of {feature}") axes[0, 1].set_ylabel(feature) i = 2 feature = features[i] axes[1, 0].boxplot(data[feature].dropna()) axes[1, 0].set_title(f"Boxplot of {feature}") axes[1, 0].set_ylabel(feature) i = 3 feature = features[i] axes[1, 1].boxplot(data[feature].dropna()) axes[1, 1].set_title(f"Boxplot of {feature}") axes[1, 1].set_ylabel(feature) # 调整子图之间的距离 plt.tight_layout() # 显示图形 plt.show() # 下面借助循环来实现子图的绘制 import pandas as pd import matplotlib.pyplot as plt # 定义要绘制的特征 # 任选4个,重点是掌握子图的绘制方法 features = ["Annual Income", "Years in current job", "Tax Liens", "Number of Open Accounts"] # 设置图片清晰度 plt.rcParams['figure.dpi'] = 300 # 创建一个包含2行2列的子图布局 fig, axes = plt.subplots(2, 2, figsize = (12,10)) i = 0 while i < 4: feature = features[i] row = i // 2 # 计算当前特征在子图中的行索引,//是整除,即取整, # 之所以用整除是因为我们要的是行数 # 例如 0//2=0, 1//2=0, 2//2=1, 3//2=1 col = i % 2 # 计算当前特征在子图中的列索引,% 是取余,即取模 axes[row, col].boxplot(data[feature].dropna()) axes[row, col].set_title(f"Boxplot of {feature}") axes[row, col].set_ylabel(feature) i = i + 1 # 调整子图之间的距离 plt.tight_layout() # 显示图形 plt.show() """ enumerate()函数:enumerate()函数返回一个迭代对象,该对象包含索引和值。 语法:enumerate(iterable, start=0) 参数: iterable -- 迭代对象,迭代对象可以是列表、元组、字典、字符串等。 start -- 索引的开始值 返回值:返回一个迭代对象,该对象包含索引和值。 """ features = ['Annual Income', 'Years in current job', 'Tax Liens', 'Number of Open Accounts'] for i, feature in enumerate(features): print(f"索引 {i} 对应的特征是: {feature}") # enumerate()函数可以帮我们拿到容器中元素的内容以及内容对应的下标索引 """ 索引 0 对应的特征是: Annual Income 索引 1 对应的特征是: Years in current job 索引 2 对应的特征是: Tax Liens 索引 3 对应的特征是: Number of Open Accounts """ # 定义要绘制的特征 features = ['Annual Income', 'Years in current job', 'Tax Liens', 'Number of Open Accounts'] # 设置图片清晰度 plt.rcParams['figure.dpi'] = 300 # 创建一个包含 2 行 2 列的子图布局,其中 fig, axes = plt.subplots(2, 2, figsize=(12, 8))#返回一个Figure对象和Axes对象 # 这里的axes是一个二维数组,包含2行2列的子图 # 这里的fig是一个Figure对象,表示整个图形窗口 # 你可以把fig想象成一个画布,axes就是在这个画布上画的图形 # 遍历特征并绘制箱线图 for i, feature in enumerate(features): row = i // 2 col = i % 2 axes[row, col].boxplot(data[feature].dropna()) axes[row, col].set_title(f'Boxplot of {feature}') axes[row, col].set_ylabel(feature) # 调整子图之间的间距 plt.tight_layout() # 显示图形 plt.show()