疏锦行Python打卡 DAY 9 热力图和子图的绘制
import pandas as pddata = pd.read_csv('G:\Vscode_Code\疏锦行_Python60天打卡训练营\python60-days-challenge-master\python60-days-challenge-master\data.csv')data.info()data.head()data["Years in current job"].value_counts()data["Home Ownership"].value_counts()# 在info()中可以看到,years in current job列和Home Ownership 都是object类型
# 而在value_counts()中可以看到,这两者的特征是有顺序关系的
# 使用嵌套字典mapping进行映射
mapping = {"Years in current job":{"10+ years": 10,"2 years": 2,"3 years": 3,"< 1 year": 0,"5 years": 5,"1 year": 1,"4 years": 4,"6 years": 6,"7 years": 7,"8 years": 8,"9 years": 9},"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"])data.info()# 标签编码和独热编码在对data进行处理后,data的区别
# 进行标签编码之后,data中的那一列还是会存在,知识里面不同的object类型呗转化成了一个个数字
# 但是那一列的名称仍然存在,只是属性从object变成了int或者float
# 独热编码则是将那一列属性拆分成多个属性了,比如一个属性有五个分类,那么进行独热编码之后
# 这个属性列就从一个列变成了5个列,此时它是bool类型,如有需要得转换成int类型data.head()data.columns# 热力图用于查看数据的相关性,即可以用于连续变量,也可以用于离散变量,具体取决于使用场景和数据类型。
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt# 提取连续值特征
continuous_features = ['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'
]# 计算相关系数矩阵
correlation_matrix = data[continuous_features].corr()
# corr() 是 Pandas DataFrame 的一个方法,用于计算列与列之间的相关系数矩阵。
# corr() 计算 DataFrame 中数值列之间的相关系数,默认使用 Pearson 相关系数,返回一个对称矩阵# 设置图片清晰度
plt.rcParams['figure.dpi'] = 300# 绘制热力图
plt.figure(figsize=(12, 10))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', vmin=-1, vmax=1)
# heatmap()函数就是绘制热力图类型的函数
plt.title('Correlation Heatmap of Continuous Features')
plt.show()import pandas as pd
import matplotlib.pyplot as plt# 定义要绘制的特征
features = ['Annual Income', 'Years in current job', 'Tax Liens', 'Number of Open Accounts']
# 随便选的4个特征,不要在意对不对# 设置图片清晰度
plt.rcParams['figure.dpi'] = 300# 创建一个包含 2 行 2 列的子图布局
fig, axes = plt.subplots(2, 2, figsize=(12, 8))# 手动指定特征索引进行绘图,仔细观察下这个坐标
i = 0
feature = features[i]
axes[0, 0].boxplot(data[feature].dropna())
axes[0, 0].set_title(f'Boxplot of {feature}')
axes[0, 0].set_ylabel(feature)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()# 借助循环来实现,刚才的坐标是帮助你理解的# 定义要绘制的特征
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))# 使用 for 循环遍历特征
for i in range(len(features)):row = i // 2 # 计算当前特征在子图中的行索引,// 是整除,即取整 ,之所以用整除是因为我们要的是行数# 例如 0//2=0, 1//2=0, 2//2=1, 3//2=1col = i % 2 # 计算当前特征在子图中的列索引,% 是取余,即取模# 例如 0%2=0, 1%2=1, 2%2=0, 3%2=1# 绘制箱线图feature = features[i]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()features = ['Annual Income', 'Years in current job', 'Tax Liens', 'Number of Open Accounts']for i, feature in enumerate(features):print(f"索引 {i} 对应的特征是: {feature}")# 定义要绘制的特征
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# a / 2:普通除法,结果为浮点数(如 3 / 2 返回 1.5)。# a // 2:向下取整除法,结果为整数(如 3 // 2 返回 1)。col = i % 2axes[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()
打卡:@浙大疏锦行