在我的整个数据框中,我有两列价格和数量。这些都包含异常值。如何删除这两个列中的离群值,以使返回的数据框从这两个列中排除离群值?我可以将其应用于一个,但不确定如何将其应用于两个列。
我尝试了以下
def make_mask(df, column):
standardized = (df[column] - df[column].mean())/df[column].std()
return standardized.abs() >= 2
def filter_outliers(df, columns):
print(columns)
masks = (make_mask(df, column) for column in columns)
print(masks)
full_mask = np.logical_or.reduce(masks)
print(full_mask)
return df[full_mask]
outliersremoved_df=filter_outliers(df,['price','qty'])
我已经使用过此功能,但一次只能将其应用于一列:
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
前2个功能出错:
ValueError: too many values to unpack (expected 1)
答案 0 :(得分:0)
def cap_data(df):
for col in df.columns:
print("capping the ",col)
if (((df[col].dtype)=='float64') | ((df[col].dtype)=='int64')):
percentiles = df[col].quantile([0.01,0.99]).values
df[col][df[col] <= percentiles[0]] = percentiles[0]
df[col][df[col] >= percentiles[1]] = percentiles[1]
else:
df[col]=df[col]
return df
final_df=cap_data(df)