【发布时间】:2019-09-23 21:00:30
【问题描述】:
我正在从数据集中删除异常值。
我决定从每一列中逐一删除异常值。我有不同数量的缺失值的列。
我使用了这段代码,但它删除了包含异常值的整行,并且由于我的数据中有许多 NaN 值,我的数据行数急剧减少。
def remove_outlier(df_in, col_name):
q1 = df_in[col_name].quantile(0.25)
q3 = df_in[col_name].quantile(0.75)
iqr = q3-q1 #Interquartile range
fence_low = q1-1.5*iqr
fence_high = q3+1.5*iqr
df_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)]
return df_out
然后我决定从每列中删除异常值,并在每列中用 NaN 填充 ouliers 我写了这段代码
def remove_outlier(df_in, col_name, thres=1.5):
q1 = df_in[col_name].quantile(0.25)
q3 = df_in[col_name].quantile(0.75)
iqr = q3-q1 #Interquartile range
fence_low = q1-thres*iqr
fence_high = q3+thres*iqr
mask = (df_in[col_name] > fence_high) & (df_in[col_name] < fence_low)
df_in.loc[mask, col_name] = np.nan
return df_in
但此代码不会过滤异常值。给出了相同的结果。
这段代码有什么问题?我该如何纠正?
还有其他优雅的过滤异常值的方法吗?
【问题讨论】: