当数据集包含Python中的数值和分类变量时,如何清除异常值?

2024-10-06 06:43:51 发布

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

我想从异常值中清除数据集,但只在三个特定列中,因为其他10个列包含分类变量。那么,如何通过只引用这些特定列来清理数据呢?在

我想用像质计测距法。这就是我目前运行的代码:

import numpy as np
def outliers(x): 
       return np.abs(x- x.median()) > 1.5*(x.quantile(.75)-x.quantile(0.25))
ath2.Age[outliers(ath2.Age)]
ath2.Height[outliers(ath2.Height)]
ath2.Weight[outliers(ath2.Weight)]

在检查了我感兴趣的列中的异常值的数量之后,我不知道如何继续下去。在


Tags: 数据代码importnumpyagereturndefas
1条回答
网友
1楼 · 发布于 2024-10-06 06:43:51

如果您希望代码是动态的,您可以首先通过下面的代码检查不属于类别的列:

cols = df.columns
num_cols = df._get_numeric_data().columns 
##num_cols will contains list of column names which are numeric
## In your case, it should come Age,Height etc.

或者,也可以根据您的数据帧使用include或{}参数

在此运行之后,下面的代码来自上面的列:

^{pr2}$

如果您只想用数字列创建一个新的df,并一次性找出异常值,代码如下:

df[df.apply(lambda x: np.abs(x - x.mean()) / x.std() < 3).all(axis=1)]

相关问题 更多 >