python - pandas 中的相关矩阵不考虑某些列

标签 python pandas correlation

我正在使用包含 39 个属性(38 个独立特征 + 类属性)的数据集来解决分类问题。当我尝试计算相关矩阵时,不考虑类属性。据我所知,它也应该包含在矩阵中。

len(heartdata.columns)
39

由于我的数据帧中的列数为 39,因此相关矩阵的形状应为 (39,39),但我得到的是:

cor = heartdata.corr()
cor.shape
(38, 38)

最佳答案

如果您的特征是分类的,您应该使用LabelEncoding

from sklearn.preprocessing import LabelEncoder

train = train_df   
label_encoder = LabelEncoder()

for i in range(len(train.columns)):
    column = train_df.columns[i]
    train[column] = label_encoder.fit_transform(train_df[column])
    print(f"train {column} uniques: {len(train[column].unique())} ")

x = train
y = train_df['gender'].to_frame(name='gender')

然后就可以得到相关矩阵:

cor = x.corr()
print(cor)

如果您想使用绘图来显示特征之间的相关性,我建议使用heatmap绘图:

import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(10,8),linewidth=10,edgecolor="#04253a" )
sns.heatmap(cor, annot=True, cmap=plt.cm.Reds)
plt.show()

输出: enter image description here

关于python - pandas 中的相关矩阵不考虑某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67252076/

相关文章:

python - SWIG Python包装,除法运算符重载很奇怪

python - 设置 matplotlib xlimits(使用 Pandas DataFrame)

python - 使用条件语句的 Pandas 样式

matlab - 典型相关分析

python - 两个二值图像之间的相关性

python - 如何仅可视化高相关性以更好地表示巨大的相关矩阵?

python - 当我尝试安装 ordered-set 时出现 UnicodeDecodeError

python - 如何排查 Azure ML 服务部署问题?

python - 使用多个表中的数据的唯一约束(SQL/SQLAlchemy)

python-3.x - 获取pandas数据框中子节点的所有直接中间和最终父节点