计算特征与目标变量之间的相关性

2024-09-27 07:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

计算我的特征和目标变量之间的相关性的最佳解决方案是什么??我的数据框有1000行和40000列。。。

示例:

df = pd.DataFrame([[1, 2, 4 ,6], [1, 3, 4, 7], [4, 6, 8, 12], [5, 3, 2 ,10]], columns=['Feature1', 'Feature2','Feature3','Target'])

这段代码运行良好,但在我的数据帧上太长。。。我只需要相关矩阵的最后一列:与目标相关(而不是成对特征相关)。

corr_matrix=df.corr()
corr_matrix["Target"].sort_values(ascending=False)

np.corcoeff()函数与数组一起工作,但是可以排除成对特征相关吗?


Tags: columns数据示例target目标dataframedf特征
2条回答

您可以在每个功能列上使用scipy.stats.pearsonr,如下所示:

import pandas as pd
import numpy as np
from scipy.stats import pearsonr

# example data
df = pd.DataFrame([[1, 2, 4 ,6], [1, 3, 4, 7], [4, 6, 8, 12], [5, 3, 2 ,10]],
                  columns=['Feature1', 'Feature2','Feature3','Target'])

# Only compute pearson prod-moment correlations between feature
# columns and target column
target_col_name = 'Target'
feature_target_corr = {}
for col in df:
    if target_col_name != col:
        feature_target_corr[col + '_' + target_col_name] = \
            pearsonr(df[col], df[target_col_name])[0]
print("Feature-Target Correlations")
print(feature_target_corr)

您可以在每个列上使用pandascorr

df.drop("Target", axis=1).apply(lambda x: x.corr(df.Target))

相关问题 更多 >

    热门问题