我正在清理一个大型数据框以用于机器学习线性回归模型。我想删除与因变量相关性低于 0.5 和高于 -.5 的列。以尽可能少的代码完成此任务的最佳方法是什么?这是我正在尝试解决的失败尝试的示例:
df.drop(df.loc[:, df.corrwith(df['saleprice'])] <.5 & > -.5, axis=1, inplace=True)
最佳答案
使用Series.between
使用 inclusive=False
并删除列更改逻辑 - 通过 ~
反转来获取与掩码不匹配的所有列:
df = pd.DataFrame({
'a':[4,5,4,5,5,4],
'b':[7,8,9,4,2,3],
'c':[1,3,5,7,1,0],
'saleprice':[5,3,6,9,2,4],
})
df1 = df.loc[:, ~df.corrwith(df['saleprice']).between(-.5, .5, inclusive=False)]
print (df1)
c saleprice
0 1 5
1 3 3
2 5 6
3 7 9
4 1 2
5 0 4
详细信息:
print (df.corrwith(df['saleprice']).between(-.5, .5, inclusive=False))
a True
b True
c False
saleprice False
dtype: bool
关于python - 如何根据数据框中与另一列的相关性删除多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59764191/