我想从异常值中清除数据集,但只在三个特定的列中清除,因为其他10个列包含分类变量。那么如何仅通过引用这些特定列来清理数据呢?
我想使用iqr range方法。那是我到目前为止运行的代码:
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)]
在检查了我感兴趣的列中的异常值之后,我不知道如何进一步进行操作。
答案 0 :(得分:0)
如果您希望代码是动态的,则可以通过以下代码首先检查未归类的列:
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
来使用exclude
或df.select_dtypes
参数
在此之后,从上方的列中运行以下代码:
df[np.abs(df.Data-df.Data.mean()) <= (3*df.Data.std())]
## Df is the dataframe and Data is the name of the column.
#In your case, it will be Age,Height etc.
OR
如果要仅用数字列制作新的df并一次性找出离群值,则代码如下:
df[df.apply(lambda x: np.abs(x - x.mean()) / x.std() < 3).all(axis=1)]