我尝试使用创建的以下函数删除异常值,但是使用它后得到的值很奇怪。我删除异常值的方法正确吗?
def remove_outliers(df,numeric_features):
'''
remove_outliers is a function which removes outliers by removing any
point above the mean by 2 standard deviations or below the mean by 2 standard deviations
df is the dataframe which the outliers are to be removed from
numeric_features are the numeric columns which might contain outliers
return new data frame
'''
#Iterate all the columns in numeric features
for col in numeric_features:
mean = df[col].mean() #Find mean of column
std = np.std(df[col],axis = 0)#find standard deviation of column
#Variables used to find outliers
above_outliers = mean + 2*std
below_outliers = mean - 2*std
outlier_indexes = df[col].loc[lambda x: (x>=above_outliers)|(x<=below_outliers)]
#drop outliers from the dataframe column
df= df.drop(outlier_indexes.index)
return df
答案 0 :(得分:0)
尝试如下
df1= df[(df['col']>=below_outliers)&(df['col']<=above_outliers))